java中子类继承父类代码运行顺序

顺序是:

1.父类静态代码块

2.子类静态代码块

3.父类代码块

4.父类构造

5.子类代码块

6.子类构造



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

现在我们有两个类 

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.子类构造


猜你喜欢

转载自blog.csdn.net/shytan/article/details/77574469