The static keyword in Java can only be used for member variables or statement blocks, and cannot be used for local variables.
When a static statement is executed for the first time when class information is loaded (such as calling static methods of classes, accessing static members, or calling constructors ), the initialization of static statements and static member variables will be executed before other statements, and will only be executed once when the class information is loaded. Other accesses to this class or new objects will not be executed.
Instead of static statements or member variables, the execution sequence is after the static statement is executed. Before the constructor is executed, the execution sequence is as follows:
1. Static statements and static member variables of the parent class
2. Static statements and static member variables of subclass
3. Non-static statement blocks and non-static member variables of the parent class
4. constructor of the parent class
5. Non-static statement blocks and non-static member variables of child classes
6. Subclass Construction Method
See the following example.
Bell. Java
public class Bell { public Bell(int i) { System.out.println("bell " + i + ": ding ling ding ling..."); }}
Dog. Java
public class Dog { // static statement static String name = "Bill"; static { System.out.println("static statement executed"); } static Bell bell = new Bell(1); // normal statement { System.out.println("normal statement executed"); } Bell bell2 = new Bell(2); static void shout() { System.out.println("a dog is shouting"); } public Dog() { System.out.println("a new dog created"); }}
Test. Java
public class Test { public static void main(String[] args) { // static int a = 1; this statement will lead to error System.out.println(Dog.name); Dog.shout(); // static statement would execute when Dog.class info loaded System.out.println(); new Dog(); // normal statement would execute when construct method invoked new Dog(); }}
Program output:
Static statement executed
Bell 1: Ding Ling...
Bill
A dog is shouting
Normal statement executed
Bell 2: Ding Ling...
A new dog created
Normal statement executed
Bell 2: Ding Ling...
A new dog created
It can be seen that when the static member variable name of the Dog class is accessed for the first time, both the static statement block and the member variable are initialized once, and when the static method shout () or constructor is called in the future, static statement blocks and member variables are not loaded again.
When the new dog () constructor is called, initialization of non-static statement blocks and member variables is performed, and the constructor content is executed.