一段代码看懂Java类的加载和初始化

先贴代码

class Base {
	int a = numa();  
	private static int c = numc(); 
	static int b = numb();
	static {
		System.out.println("Base:static code block..");  
	}
	Base(){
		System.out.println("Base:constructor..."); 
	}

	static int numa(){
		System.out.println("Base:int a..."); 
		return 1;
	}
	static int numb(){
		System.out.println("Base:static int b...");
		return 1;
	}
	static int numc(){
		System.out.println("Base:private static int c...");
		return 1;
	}
}

class A extends Base{  
	private static int l = numl();
	private int m = numm();
	static{  
		System.out.println("A:static code block...");
	}
	A(){  
		System.out.println("A:constructor..."); 
	}   
	static int numl() {  
		System.out.println("A:static int l...");  
		return 1;  
	}  
	int numm() {  
		System.out.println("A:private int m...");  
		return 1;  
	}

}

public class Test{
	public static void main(String[] args){
		new A();
	}
}

输出结果如下:

Base:private static int c...
Base:static int b...
Base:static code block..
A:static int l...
A:static code block...
Base:int a...
Base:constructor...
A:private int m...
A:constructor...


从输出结果很直观的看出初始化的顺序。静态到实例,父类到子类,实例化的时候构造器就开始工作了。

总结:先加载父类,再加载子类,然后初始化父类static,然后初始化子类static,然后执行父类构造函数,最后执行子类构造函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值