I recently read Sun weiqin's book on Java object-oriented, and I have seen a more systematic discussion of class initialization and loading in Java.
1) class initialization. When Java initializes a class, the following steps are performed:
A. If the class has a direct parent class and the parent class has not been initialized, initialize the direct parent class first.
B. If the class has initialization statements, execute these initialization statements directly.
For example
Package Init;
Class base {
Static int A = 1;
Static {
System. Out. println ("init base ");
}
}
Class sub extends base {
Static int B = 1;
Static {
System. Out. println ("init Sub ");
}
}
Public class inittester {
Static {system. Out. println ("init inittester ");}
/*
Public static void main (string ARGs []) {
System. Out. println ("B =" + sub. B); // when executing this line of code, initialize the base class and sub class in sequence.
}
*/
Output:
Init inittester
Init Base
Init sub
B = 1
Assume that
Public static void main (string ARGs []) {
Base base; // The base class is not initialized.
System. Out. println ("After defining base ");
Base = new base (); // when this line of code is executed, the base class is initialized.
System. Out. println ("after creating an object of base ");
System. Out. println ("A =" + base. );
System. Out. println ("B =" + sub. B); // when this line of code is executed, only the sub class is initialized.
}
}
Output
Init inittester
After defining Base
Init Base
After creating an object of Base
A = 1
Init sub
B = 1
2) class initialization time
For final type A, if the value of the variable can be calculated during compilation, class initialization will not be caused, as shown below:
Class tester {
Public static final int A = 2*3;
Static {
System. Out. println ("hello ");..............
}
}
Public class sample
{
Public static void main (string ARGs [])
{System. Out. println ("A =" + tester. );
}
}
2) package initbase;
Class base {
Static int A = 1;
Static {
System. Out. println ("init base ");
}
Static void method (){
System. Out. println ("method of base ");
}
}
Class sub extends base {
Static {
System. Out. println ("init Sub ");
}
}
Public class sample {
Public static void main (string ARGs []) {
System. Out. println ("A =" + sub. a); // only initialize the base class.
Sub. Method ();
}
}
Because static variables A and static method () are defined in the base parent class, only the base class is initialized and the sub class is not initialized.
The printed result is
Init Base
A = 1
Method of Base
In this case, if you call tester. A, no hello will be output,