第一次实例化一个类时,初始化优先顺序为:
1、父类中的静态成员变量和静态代码块初始化
2、本类中的静态成员变量和静态代码块初始化
3、父类中的实例成员初始化
4、父类中的构造方法
5、本类中的实例成员初始化
6、本类中的构造方法
成员变量和示例变量初始化的区别:
成员变量:每次新建对象的时候都会初始化;
实例变量:只在第一次调用(包括实例化或通过类访问)的时候一次性初始化全部的静态变量
实例变量示例:
class Tag { Tag(int marker) { System.out.println("Tag(" + marker + ")"); } } class Card { Tag t1 = new Tag(1); // Before constructor Card() { // Indicate we're in the constructor: System.out.println("Card()"); t3 = new Tag(33); // Re-initialize t3 } Tag t2 = new Tag(2); // After constructor void f() { System.out.println("f()"); } Tag t3 = new Tag(3); // At end } public class OrderOfInitialization { public static void main(String[] args) { Card t = new Card(); t.f(); // Shows that construction is done } }
运行结果:
Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
静态变量示例:
public class Bowl { Bowl(int marker) { System.out.println("Bowl(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } public class Table { static Bowl b1 = new Bowl(1); Table() { System.out.println("Table()"); b2.f(1); } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static Bowl b2 = new Bowl(2); } public class Cupboard { Bowl b3 = new Bowl(3);//注意实例变量与静态变量共存的时候,即使静态变量靠后,也先初始化 static Bowl b4 = new Bowl(4); Cupboard() { System.out.println("Cupboard()"); b4.f(2); } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static Bowl b5 = new Bowl(5); } public class Test { public static void main(String[] args) throws Exception { System.out.println( "Creating new Cupboard() in main"); new Cupboard(); System.out.println( "Creating new Cupboard() in main"); new Cupboard(); t2.f2(1); t3.f3(1); } static Table t2 = new Table(); static Cupboard t3 = new Cupboard(); }
运行结果:
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)