JVM学习笔记10——初始化对于类与接口的异同点深入解析

public class MyTest5 {

    public static void main(String[] args){

        System.out.println(MyChild5.b);

        System.out.println(MyChild6.thread);
    }

}

interface MyParent5 {
    public static final int a = 5;
    // public static final int a = new Random().nextInt(2); 如果删掉MyParent5的class文件会报错

    public static Thread thread = new Thread(){
        {
            // 运行之后不会输出,说明接口没有初始化
            System.out.println("MyParent5 invoked");
        }
    };

}

class MyChild5 implements MyParent5 {
   public static int b = 5;
}

运行会发现不会输出MyParent5 invoked 初始化时并不会初始化父接口,当一个类被初始化的时候,它所实现的接口是不会被初始化的

interface MyGrandpa5{
    public static Thread thread = new Thread(){
        {
            // 运行之后不会输出,说明接口没有初始化
            System.out.println("MyGrandpa5 invoked");
        }
    };
}

interface MyParent5 extends MyGrandpa5{

    public static Thread thread = new Thread(){
        {
            // 运行之后不会输出,说明接口没有初始化
            System.out.println("MyParent5 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 extends MyGrandpa5_1{
    public static Thread thread = new Thread(){
        {
            // 运行之后不会输出,说明接口没有初始化
            System.out.println("MyParent5_1 invoked");
        }
    };
}

只会输出MyParent5_1 invoked,初始化一个接口的时候并不会初始化他的父接口

当一个接口在初始化时,并不要求其父接口都完成初始化
只有在真正使用到父接口的时候(如引用接口中所定义的常量时),才会导致父接口初始化
因为接口中都是常量,单static就不行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值