I. Definition of instance variables and class variables
The variables of a Java program can be divided into member variables and local variables.
- Local variables (short acting time, stored in the stack of methods)
- Formal parameter: defined by the method signature, which is assigned by the method caller, and dies with the end of the method.
- Local variables within a method: Defined inside a method, must be explicitly initialized within the method. Comes into effect from the completion of initialization and dies with the end of the method.
- Local variables within a code block: defined within a code block, must be explicitly initialized within a block of code. After initialization is complete, it takes effect and dies with the end of the code block.
- Member variables (variables defined within the class)
- Instance variable (non-static variable): no static modifier
- Class variable (static variable): static modifier
Note: The role of static changes the instance member to a class member, and only the members in the class are decorated.
Public classerrordef{//The following code will prompt: illegal forward reference intNUM1 = num2 + 2; intnum2 = 20;} Public classerrordef2{//The following code will prompt: illegal forward reference Static intNUM1 = num2 + 2; Static intnum2 = 20;} Public classrightdef{//The following code is completely normal intNUM1 = num2 + 2; Static intnum2 = 20;}
Ii. properties of instance variables and class variables
Within the same JVM, each class corresponds to only one class object, but each class can create multiple Java objects. Since each class corresponds to only one class object, a variable of a class within the same JVM requires only one memory space, and for instance variables, each time the class is created, it needs to allocate a chunk of memory space to the instance variable.
classperson{String name; intAge ; Static intEyenum;} Public classfieldtest{ Public Static voidMain (string[] args) {Person.eyenum= 2;//------(1)System.out.println (Person.eyenum); Person P=NewPerson (); P.name= "Pig"; P.age= 300; System.out.println (p.eyenum);//----(2)Person P2=NewPerson (); P2.name= "Monkey King"; P2.age= 500; P2.eyenum= 3;//------(3)System.out.println (P.eyenum); System.out.println (P2.eyenum); System.out.println (Person.eyenum); }}
The memory allocation process for the above code is as follows:
object and Memory control 1---Instance variables and class variables