接口初始化规则
当一个接口在初始化时,并不要求其父接口都完成了初始化
只有在真正使用父接口的时候 (如引用接口中所定义的常量时),才会初始化
public class MyTest5 {
public static void main(String[] args) {
System.out.println(MyChild5.b);
}
}
interface MyParent5 {
public static int a = 5;
}
interface MyChild5 extends MyParent5 {
public static int b = 6;
}
类加载器准备阶段
准备阶段会给
- counter1 赋初值 0
- singleton 赋初值 null
- counter2 赋初值 0
构造方法不会执行
public class MyTest6 {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println("counter1: " + Singleton.counter1);
System.out.println("counter2: " + Singleton.counter2);
}
}
class Singleton {
public static int counter1 = 1;
private static Singleton singleton = new Singleton();
private Singleton() {
counter1++;
counter2++;
System.out.println(counter1);
System.out.println(counter2);
}
public static int counter2 = 0;
public static Singleton getInstance() {
return singleton;
}
}
输出为
2
1
counter1: 2
counter2: 0
类加载器初始化阶段
初始化阶段开始进行真正赋值
- counter1 显式的赋值为 1
- singleton 的值会导致构造方法的执行,导致 counter1++ 变为 2,counter2++ 变为 1
- counter2 = 0,会导致 counter2 的值变为 0