学习学习类初始化的时候看到了下面关于接口的两大结论:

  • 在初始化一个类时,并不会初始化它所实现的接口
  • 在初始化一个接口时,并不会先初始化它的父接口  因为接口中的变量都是 public static final 的,所以我一直在想,如何才能让接口初始化呢。直到我看到了网上的一个例子:
public class InterfaceTest {
	public static void main(String[] args) {
		System.out.println(Parent.thread);
	}
}

interface Parent {
	public static final int a = 1;

	public static Thread thread = new Thread(){
		{
			System.out.println(a);
		}
	};

	public static Thread thread2 = new Thread(){
		{
			System.out.println(a + 1);
		}
	};

}

1 2 Thread[Thread-0,5,main]

 接下来我们来验证一下上面两个结论

interface Parent {

	public static int a = 1;

	public static Thread thread = new Thread(){
		{
			System.out.println("Thread...Parent");
			System.out.println(a);
		}
	};
	
}

class Child implements Parent {
	public static int b = 5;
}
public class InterfaceTest {

	public static void main(String[] args) {
		System.out.println(Child.b);
	}
}

5

 对于上面那段程序,我们发现只输出了5,而没有输出"Thread...Parent",这就说明了在初始化一个类时,并不会初始化它所实现的接口

 我们修改一下程序,将Child改为接口

interface Child extends Parent {
	public static  int b = 5;
	public static Thread thread = new Thread(){
		{
			System.out.println("Thread...Child");
			System.out.println(a);
		}
	};
}

public class InterfaceTest {
	public static void main(String[] args) {
		System.out.println(Child.thread);
	}
}

Thread...Child 1 Thread[Thread-0,5,main]

 对于修改后的程序,我们发现并没有输出“Thread...Parent",这就说明了在初始化一个接口时,并不会先初始化它的父接口