Initialization for similarities and differences between classes and interfaces in-depth analysis

When the Java virtual machine to initialize a class, asking it to all of the parent class have been initialized, but this rule is not suitable interfaces

1) When a class is initialized, and will not be initialized class interfaces it implements.

2) When initializing an interface, and will not be initialized its parent interface

Thus, a parent interface and sub-interface because it does not implement class initialization or initialized. Only when the program for the first time using the lens variable specific interface, will cause the initialization of the interface.

 

When a class is initialized, and will not be initialized interfaces it implements the class Sample

public class MyTest5 {

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

interface MyParent5{


    public static Thread thread = new Thread(){
        {
            //实例化代码块
            System.out.println("MyParent 5 invoked ");
        }
    };

}

class MyChild5 implements MyParent5{
    public static  int b = 6;

}

  Print results

6

  

If the access interface to change class

public class MyTest5 {

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

    }
}

class MyParent5{

  
    public static Thread thread = new Thread(){
        {
            //实例化代码块
            System.out.println("MyParent 5 invoked ");
        }
    };

}

class MyChild5 extends MyParent5{
    public static  int b = 6;

}

  It will print out

MyParent 5 invoked this sentence.

 

 At initialization interface, and it will not be initialized its parent interface

public class MyTest5 {

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



interface MyGrandpa5_1 {
    public static Thread thread = new Thread(){
        {
            //实例化代码块
            System.out.println("MyGrandpa5_1 invoked ");
        }
    };
}

interface MyParent5_1 {
    public static  Thread thread = new Thread(){
        {
            //实例化代码块
            System.out.println("MyParent5_1 invoked ");
        }
    };
}

  Print results

MyParent5_1 invoked 
Thread[Thread-0,5,main]

  

Guess you like

Origin www.cnblogs.com/linlf03/p/10990981.html