First, static members are initialized during class loading, and the classloader of JVM is loaded. For the first time, they actively use loading, rather than static members are creating objects, it is initialized only when the new operation is performed;
The order is loading before initialization. Static members are initialized during loading. Non-static members cannot be used if they are not loaded yet, the non-static member is initialized when an object is created through the new operator after the class is loaded. The static member has allocated memory space, so it can be accessed!
To put it simply, a static member belongs to a class and does not need to be generated. Instead of being static, an object must be generated.
Therefore, static members cannot directly access the service.
The static features are described below:
1. Loading with classes
That is to say, static will disappear with the disappearance of the class, indicating the longest static lifecycle.
2. takes precedence over the existence of Objects
Specifically: static objects exist first and then
3. shared by all objects
4. It can be directly called by multiple class names
Differences between instance variables and class variables
1. storage location
Class variables exist in the method area as classes are loaded, and instance variables exist in the heap memory as object objects are established.
2. Lifecycle
The lifecycle of a class variable is the longest. It is loaded with the loading of the class and disappears with the disappearance of the class.
Instance variables disappear with the disappearance of "object"
Static usage considerations:
1. Static methods can only access static members (including member variables and member methods)
Non-static methods can access static or non-static methods
2. This and super keywords cannot be defined in static methods.
The keyword "this" or "super" cannot appear in static methods because the static method takes precedence over the object.
3. The main function is static.
Static advantages and disadvantages
Benefits: the shared data of objects is stored separately to save space. There is no need to store one copy of all objects.
Can be called directly by Class Name
Disadvantage: the lifecycle is too long, and access is limited (only static access is allowed)