Class variable, instance variable

Source: Internet
Author: User

 

1 ) Instance variables and class variables
Memory is allocated to instance variables of each object.;
Class variable (that is Static Variable)Allocate memory only when the first object is generated,All instance objects share the same class variable,Changes to class variables of each instance object will affect other instance objects..Class variables can be directly accessed by class names,You do not need to create an instance object, or you can use the Instance Object Sequence class variable.

The difference is:Class variables are shared by all objects, and one of them changes its value. Other objects get the changed result;WhileInstance variables are private objects. A certain object changes its value without affecting other objects;

Example:

Public Class {

Static int A = 0 ;//Class variable

Private int B = 0 ;//Strength Variable

}

Public Class B {

Public void main (string [] ARGs ){

A a1 = new ();

A a2 = new ();

A1.a = 3 ;//EquivalentA. A = 3;

A1. B = 4;

System. Out. println (a2.a );// Result: 3 ,Class variables are for all objects, so A1 Change A , A2 Of A Also changed

System. Out. println (a2. B );// Result: 0 , The instance only changes its own, so A1 Object B Change without affecting objects A2 Of B Variable

}}

2 ) Instance methods and class methods
The instance method can operate the instance variables of the current object, or the class variables. The instance method is called by the instance object.
HoweverClass MethodYou cannot access instance variables. You can only access instance variables.. Class methods can be called directly by class names,It can also be called by instance objects.Class methods cannot be used This Or Super Keyword.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.