一、最普通的情况
/*
*子父类构造函数的特点,当子父类都有构造函数时,先执行父类的构造函数,再执行子类的构造函数。
*因为子类所有的构造函数中的第一行都有一句隐式语句:super();//默认调用父类空参数的构造函数
*
*为什么呢?
*原因:子类会继承父类中的内容,所以子类在初始化时,必须先到父类中去执行父类的初始化动作。
*/
class Father{
Father(){
System.out.println("父 constructor run");
}
}
class Son extends Father{
Son(){
//super(); 这句为隐式语句,意思是调用父类空参数的构造函数
System.out.println("子 constructor run");
}
}
public class extendsDemo {
public static void main(String[] args) {
new Son();
/*执行结果如下,先执行父类构造函数,再执行子类构造函数*/
//父 constructor run
//子 constructor run
}
}
二、父类构造函数没有空参数构造函数的情况
/*
* 若父类没有空参数构造函数时,
* 子类的构造函数必须通过显式的super语句指定要访问的父类构造函数
*/
class Father{
Father(int x){
System.out.println("父 constructor run"+x);
}
}
class Son extends Father{
Son(int x){
super(x); //这句必须有,因为父类没有空参数的构造函数,所以隐式的super()无效,而且要放第一行,因为初始化动作要先执行
System.out.println("子 constructor run"+x);
}
}
public class extendsDemo {
public static void main(String[] args) {
new Son(6);
/*执行结果如下,先执行父类构造函数,再执行子类构造函数*/
//父 constructor run 6
//子 constructor run 6
}
}