JVM05-接口初始化和类加载分析学习

public class interfaceLoader {

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

interface ParentInter {

    Integer parent =  1;

}

interface ChildInter extends ParentInter {

    Integer child =  2;

}

上面实例可以得出:

  1. 当一个接口初始化时,并不要求其父接口都完成初始化。这个就和类的主动使用截然相反,类要求其父类不许全部初始化化。
    2.只有真正使用到父类接口的时候(如,引用接口中所定义的常量的时候),才会被初始化。
public class interfaceLoader {

    public static void main(String[] args) {
    	/**
    	*	这个地方调用getSingleton方法,而这个方法有new了Singleton对象。
    	*	对Singleton的主动使用,导致类初始化 成员变量
    	*/	
        Singleton singleton = Singleton.getSingleton();
        
        System.out.println("--1.->"+Singleton.counter1);
        System.out.println("--2.->"+Singleton.counter2);
    }
}

class Singleton{

    public static int counter1;

    public static int counter2 = 0;

    private static Singleton singleton = new Singleton();
	/**
	* 上面对类主动使用,使得类初始化,为counter1和counter2赋初始值
	*/
    private  Singleton(){
    	//这其实也是准备阶段,只不过初始化的时候没有在给她们赋值,所以保持了原样
        counter1++; //1
        counter2++; //1
    }

    public static Singleton getSingleton(){
        return singleton;
    }
}

在这里插入图片描述

public class interfaceLoader {

    public static void main(String[] args) {
    /**
    * 同样的方式导致类的主动使用初始化
    */
        Singleton singleton = Singleton.getSingleton();
        System.out.println("--1.->"+Singleton.counter1);
        System.out.println("--2.->"+Singleton.counter2);
    }
}

class Singleton{

    public static int counter1;

    private static Singleton singleton = new Singleton();

    private  Singleton(){
    	//准备阶段,为变量赋予初始值,只不过这里的默认初始值做了运算
        counter1++;
        counter2++;
        System.out.println("counter1:"+counter1);
        System.out.println("counter2:"+counter2);
        System.out.println("上面是准备阶段为变量赋值....");
    }
	//初始化阶段,为变量又赋了值。counter2为初始化阶段,主要是他是在new Singleton()
	//之后完成的。比如counter1,它在new 之前赋值1,初始化时变成2,即使他和counter2在同
	//一层,但是它并没有造成值的重新赋值。
    public static int counter2 = 0;

    public static Singleton getSingleton(){
        return singleton;
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值