首页 > 其他 > 详细

初始化对于类和接口的异同点深入解析

时间:2019-06-08 17:02:31      阅读:99      评论:0      收藏:0      [点我收藏+]

当Java虚拟机初始化一个类时,要求它的所有父类都已经初始化,但是这条规则不适于接口

1) 当初始化一个类时,并不会先初始化它所实现的类的接口。

2) 在初始化一个接口时,并不会先初始化它的父接口

因此,一个父接口并不会因为它的子接口或者实现类的初始化而初始化。只有当程序首次使用特定接口的镜头变量时,才会导致该接口的初始化。

 

当初始化一个类时,并不会先初始化它所实现的类的接口 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;

}

  打印结果

6

  

如果接接口改为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;

}

  那么就会打印出

MyParent 5 invoked 这句话。

 

 在初始化一个接口时,并不会先初始化它的父接口

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 ");
        }
    };
}

  打印结果

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

  

初始化对于类和接口的异同点深入解析

原文:https://www.cnblogs.com/linlf03/p/10990981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!