Definition of instance variables and class variables
When declaring member variables, those modified with the keyword static are called class variables. Class variables are also called static variables or static variables, while those that are not modified with the keyword static are called instance variables.
For example:
classMain{floatx;//instance variable staticinty;//class variable}
Notice:
The keyword static needs to be placed before the type of the variable.
The difference between instance variables and class variables
1. The instance variables of different objects are different from each other:
A class can create multiple different objects by using the new operator. These objects will be assigned different member variables. The instance variables assigned to different objects occupy different memory spaces. Changing the instance variables of one object will not affect the other objects. Instance variables of the object.
2. All objects share class variables:
If there are class variables in the class, when using the new operator to create multiple different objects, the class variables assigned to these objects occupy the same memory. Changing the class variable of one object will affect the class of other objects. Variables, that is to say objects share class variables.
3. Directly access class variables through class names:
When a Java program is executed, the bytecode file of the class is loaded into memory. If the class does not create an object, the instance variables in the class will not be allocated memory. However, the class variables in the class are allocated corresponding memory space when the class is loaded into memory. If this class creates objects, then the instance variables of different objects are different from each other, that is, different memory spaces are allocated, and the class variables no longer reallocate memory. All objects share class variables, that is, the class variables of all objects are the same. The memory space occupied by class variables is not released until the program exits.
Therefore, a class variable can be accessed not only through an object but also directly through the class name, while the instance variables of an object can be accessed through the object but not using the class name.