java 子类继承父类运行顺序

平时项目经常用到 子类继承父类 但对执行顺序一直不太清楚,花时间捋一捋,重新学习一下,感觉有些收获

现在我们有两个类 

public class TestSta1 {
	
	static {
		System.out.println("this static TestSta1    	<span style="white-space:pre">	</span>1");
	}
	
	{
		System.out.println("this TestSta1		<span style="white-space:pre">	</span>3");
	}
	
	public TestSta1(){
		System.out.println("this TestSta1(str)		<span style="white-space:pre">	</span>4");
	}
	
}


public class TestSta2 extends TestSta1{
	
	public TestSta2() {
		System.out.println("this TestSta2()       		7");
	}
	
	static{
		System.out.println("this static testSta2    	<span style="white-space:pre">	</span>2");
	}
	
	{
		System.out.println("this teststa2		5");
	}
	
	{
		System.out.println("this teststa2		6");
	}
	
	public static void main(String[] args) {
		new TestSta2();
	}
	
}
执行结果  

this static TestSta1    	1
this static testSta2    	2
this TestSta1			3
this TestSta1(str)		4
this teststa2		<span style="white-space:pre">	</span>5
this teststa2		<span style="white-space:pre">	</span>6
this TestSta2()       		7
我们都知道,java的机制是先编译成字节码文件.class  然后在JVM上解释器逐行翻译成机器码文件,那从.class 到JVM加载的时候,就执行static代码块和static变量,所以先执行静态代码块,并且执行顺序是先执行父类的在执行子类的,当执行开始执行到 new TestSta2(); 

创建对象的时候,调用了它的无参构造,所有子类的构造方法第一行的时候都隐含 super()

public TestSta2() {
	super();
	// TODO Auto-generated constructor stub
}
所以会调用父类的构造方法,而每次在执行构造方法之前都会执行代码块,父类的代码块,父类的构造方法执行完毕之后,开始执行子类的代码块,构造方法,

如果我们修改一些东西

public static void main(String[] args) {
	System.out.println(" main testSta1() ``````````````````");
	new TestSta2();
}
会发现执行顺序

this static TestSta1    	1
this static testSta2    	2
 main testSta1() ``````````````````
this TestSta1			3
this TestSta1(str)		4
this teststa2		<span style="white-space:pre">	</span>5
this teststa2		<span style="white-space:pre">	</span>6
this TestSta2()       		7
静态代码块执行顺序在main方法之前

如果我们重新建个类

public class TestSta3 {
	public static void main(String[] args) {
		System.out.println("  main teststa3 ~~~~~~~~~~~~~~");
		new TestSta2();
	}
}
执行顺序

  main teststa3 ~~~~~~~~~~~~~~
this static TestSta1    	1
this static testSta2    	2
this TestSta1			3
this TestSta1(str)		4
this teststa2		<span style="white-space:pre">	</span>5
this teststa2		<span style="white-space:pre">	</span>6
this TestSta2()       		7
我的理解我们在TestSta2 起main 方法的时候,JVM会首先加载TestSta2.class的时候开始初始化静态代码块,而如果在TestSta3 起main方法,JVM会首先加载TestSta3,只有执行到 new TestSta2(); 时 会加载TestSta2.class  才会初始化静态代码块

最后总结一下执行顺序

1.父类静态代码块

2.子类静态代码块

3.父类代码块

4.父类构造

5.子类代码块

6.子类构造


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值