接口初始化规则与类加载器准备阶段和初始化阶段的重要意义分析
1.当一个接口在初始化时,并不要求其父接口都完成了初始化
当一个接口在初始化时,并不要求其父接口都完成了初始化;只有在真正使用到父类接口的时候(如引用接口中所定义的常量时),才会初始化。
对比:正常的类的继承,[当一个类在初始化时,要求其父类全部都已经初始化完毕了]
/*
当一个接口在初始化时,并不要求其父接口都完成了初始化;
只有在真正使用到父类接口的时候(如引用接口中所定义的常量时),才会初始化。
*/
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;
}
运行结果:
6
★[这里:interface中的变量本身就是 public static final 的,所以,加上之后会是冗余的[redundant],可以不加。]
另外一个:
public class MyTest5 {
public static void main(String[] args) {
System.out.println(MyChild5.b);
}
}
interface MyParent5{
public static int a = new Random().nextInt(1);;
}
interface MyChild5 extends MyParent5{
public static int b = 5;
}
运行结果:
5
/**因为:只有在真正使用到父类接口的时候(如引用接口中所定义的常量时),才会初始化。*/
2.类加载器准备阶段和初始化阶段
-
实例一:
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; public static int counter2 = 0; private static Singleton singleton = new Singleton(); private Singleton(){ counter1++; counter2++; } public static Singleton getInstance(){ return singleton; } } 运行结果: counter1:1 counter2:1 /** 分析:因为类加载器在准备阶段会将变量赋予默认值, int 的值为 0,之后会进行初始化,初始化之后才进行counter1++;counter2++;之后打印的结果为 1、1。 */
-
实例二:★★★★★
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; private static Singleton singleton = new Singleton(); private Singleton(){ counter1++; counter2++; //准备阶段的重要意义 System.out.println(counter1); System.out.println(counter2); } //现在把counter2放在这个位置 public static int counter2 = 0; public static Singleton getInstance(){ return singleton; } } 运行结果: 1 1 counter1:1 counter2:0 /** 分析:因为类加载器在准备阶段会将变量赋予默认值, int 的值为 0(counter1,counter1都是0),之后会进行初始化,初始化之后才进行counter1++;counter2++;所以,在private Singleton(){}这个方法中的两个sout都是1,再往下面一段public static int counter2 = 0;使得counter2在初始化完成之后并进行++操作之后又被赋值为0;所以,才致使最终的打印结果为:counter1:1;counter2:0 */