■ The general order of class initialization is:
1 - First all static items are initialized, in their source code order..
2 - Then all member variables are initialized.
3 - Lastly the constructor is called.
■ Below is a simple demonstration program showing class initialization order. Its output is:
1a - Static class variable vstatic initialized first.
1b - Static initialization block ran.
2 - Non-static class variable vnonstatic initialized.
3 - Constructor ran.
public class ExecuteDemo {
public static void main(String[ ] args) {
DemonstrateOrder DO = new DemonstrateOrder ( ); }
}
class DemonstrateOrder{
static String vstatic = verify(" 1a - Static class variable vstatic initialized first." );
String vnonstatic = verify(" 2 - Non-static class variable vnonstatic initialized." );
static {System.out.println(" 1b - Static initialization block ran." ); }
static String verify(String s) { System.out.println(s); return s; }
DemonstrateOrder ( ) {System.out.println(" 3 - Constructor ran." ); }
}
■ The general order of initialization for classes with inheritance is:
First, parent static items, then child static items
Then parent member variables, followed by the parent constructor
Then child member variables, followed by the child constructor
Read full article from initialization order
No comments:
Post a Comment