在继承中,子类所有的构造方法默认访问父类中的无参构造,子类中每一个构造方法第一条语句默认为super();
class Father{
public Father(){
System.out.println("父类无参构造");
}
public Father(String s){
System.out.println("父类有参构造");
}
}
class Son extends Father{
public Son(){
//super();默认存在
System.out.println("子类无参构造");
}
public Son(String s){
//super();默认存在
System.out.println("子类有参构造");
}
}
public class Extend {
public static void main(String[] args) {
String s="can";
Son s1=new Son();
System.out.println("--------");
Son s2=new Son(s);
}
}
结果输出为:
父类无参构造
子类无参构造
----------
父类无参构造
子类有参构造
因为子类继承父类的数据,将来还会使用父类的数据,所以子类初始化之前要先完成父类初始化。
本文详细解析了Java中子类构造方法如何默认调用父类无参构造方法的机制,并通过示例代码展示了子类构造过程及输出结果。
1400

被折叠的 条评论
为什么被折叠?



