当Java 虚拟机初始化一个类时,要求它的所有父类都已经被初始化,但是这条规则并不适用于接口。
在初始化一个接口时,并不会先初始化它的父接口。
在初始化一个类时,并不会先初始化它所实现的接口。
因此,一个父接口并不会因为它的子接口或者实现类的初始化而初始化。只有当程序首次使用特定接口的静态变量时,才会导致该接口的初始化。
示例1:
public class MyTest5 {
public static void main(String[] args) {
System.out.println(MyChild5.b);
new C();
new C();
}
}
//接口中的常量 默认是 final, 类中的常量如果没定义为final那它就不是final
interface MyParent5 {
//public static int a = new Random().nextInt(3);
public static int a = 5;
}
interface MyChild5 extends MyParent5 {
public static int b = 6;
}
class C {
static { //AA
System.out.println("hello");
}
public C(){
System.out.println("c");
}
}
此处结果输出为
6
hello
c
c
分析:
若将AA处的static去掉, 则每次在new C()时, AA处的代码块都会执行
示例2
在初始化一个接口时,并不会先初始化它的父接口。所以此出的输出结果是 6
public class MyTest51 {
public static void main(String[] args) {
System.out.println(MyChild51.b);
}
}
//接口中的常量 默认是 final, 类中的常量如果没定义为final那它就不是final
interface MyParent51 {
public static Thread thread = new Thread(){
{
System.out.println("MyParent51 new thread...");
}
};
}
interface MyChild51 extends MyParent51 {
public static int b = 6;
}
若此处是子类继承接口, 在初始化一个类时,并不会先初始化它所实现的接口
下面示例较上面例子做了修改,由子类继承接口, 此处输出同样是 6
public class MyTest51 {
public static void main(String[] args) {
System.out.println(MyChild51.b);
}
}
//接口中的常量 默认是 final, 类中的常量如果没定义为final那它就不是final
interface MyParent51 {
public static Thread thread = new Thread(){
{
System.out.println("MyParent51 new thread...");
}
};
}
class MyChild51 implements MyParent51 { //此处修改--------------------
public static int b = 6;
}
示例3
此例子是 子类继承父类, 会导致父类先初始化, 输出结果为:
MyParent51 new thread...
6
public class MyTest51 {
public static void main(String[] args) {
System.out.println(MyChild51.b);
}
}
//接口中的常量 默认是 final, 类中的常量如果没定义为final那它就不是final
class MyParent51 {
public static Thread thread = new Thread(){
{
System.out.println("MyParent51 new thread...");
}
};
}
class MyChild51 extends MyParent51 { //此行有修改
public static int b = 6;
}
网友评论