Chapter 1 class and object knowledge points in the second quarter of Java, and section 2 of java
JavaStatic Method in
1,Static members of the same type can be called directly in static methods, but non-static members cannot be called directly.For example:
To call non-static variables in a static method, you can create a Class Object and access non-static variables through the object.. For example:
2,In common member methods, you can directly access non-static and static variables of the same type., As shown below:
3, Non-static methods cannot be called directly in static methods. You must use objects to access non-static methods.For example:
Static initialization block in Java
In Java, values can be assigned through initialization blocks. For example:
The class declaration can contain multiple initialization blocks. When a class instance is created, these code blocks are executed in sequence. Static initialization blocks are called static initialization blocks.
Note:Static initialization blocks are executed only when the class is loaded and only once. At the same time, static initialization blocks can only assign values to static variables and Cannot initialize common member variables..
Let's look at a piece of code:
Running result:
The output result shows that the static initialization block is executed first when the program is running, then the common initialization block is executed, and the constructor is executed finally. Because the static initialization block is only executed once during class loading, the static initialization block is not executed when the object hello2 is created again.