Usage: it is a modifier used to modify members (member variables, member functions ).
When a member is modified statically, an additional call method is provided. In addition to being called by an object, the member can also be called directly by the class name. Class name. Static member.
Static features:
1. Load as the class is loaded.
That is to say, the static state disappears with the disappearance of the class, indicating that it has the longest life cycle.
2. Takes precedence over object existence.
It is clear that static data exists first. Objects exist.
3. Shared by all objects.
4. It can be called directly by the class name.
Differences between instance variables and class variables:
1. Storage location.
Class variables exist in the method area as classes are loaded.
Instance variables exist in heap memory as objects are created.
2. Lifecycle.
The maximum lifecycle of a class variable. The class disappears as it disappears.
The lifecycle of instance variables disappears with the disappearance of objects.
Static usage considerations:
1. Static methods can only access static members (member variables and methods ).
Non-static methods allow both static and non-static access.
2. this super keyword cannot be defined in static methods.
Because the static state takes precedence over the object existence. Therefore, this cannot appear in static methods.
3. The main function is static.
Static has the following advantages:
Benefits: You can store shared object data in a separate space to save memory. You do not need to store one copy of each object.
Can be called directly by class name.
Disadvantage: the lifecycle is too long. Access restrictions. (Although static is good, only static access is allowed)
Static code block:
Format:
Static
{
The execution statement in the static code block.
}
Features: The class is executed only once as the class is loaded, and takes precedence over the main function execution.
Used for class initialization.
Initialization sequence:
A c d is static and then the constructor finally calls the custom constructor.