返回博主主页

java父类、子类构造函数调用过程

 

java中的构造方法调用顺序问题,举例如下:
public class Son extends Father {
SonProp r = new SonProp();
	public Son() {
		System.out.println("Son is construct");
}
	public static void main(String[] args) {
		new Son();
}
}

class Father {
FatherProp SonProp = new FatherProp();
	public Father() {
		System.out.println("Father is construct");
	}
}
class SonProp {
public SonProp() {
System.out.println("SonProp is construct");
}
}

class FatherProp {	
public FatherProp() {		
System.out.println("FatherProp is construct");	
}
}

执行结果如下:
FatherProp is construct
Father is construct
SonProp is construct
Son is construct

由此看出java类初始化时构造函数调用顺序:
(1)初始化对象的存储空间为零或null值;
(2)按顺序分别调用父类成员变量和实例成员变量的初始化表达式;
(3)调用父类构造函数;(如果实用super()方法指定具体的某个父类构造函数则使用指定的那个父类构造函数)
(4)按顺序分别调用类成员变量和实例成员变量的初始化表达式;
(5)调用类本身构造函数。

//先执行外部类构造方法,再执行内部类构造方法

  

posted @ 2021-10-12 17:45  懒惰的星期六  阅读(491)  评论(0编辑  收藏  举报

Welcome to here

主页