父类写无参构造,子类不写构造,实例化子类,会同时调用父类构造方法
public class Father {
private String name;
private int age;
public Father() {
System.out.println("父类无参构造");
}
}
public class Son extends Father {
private String name;
private int age;
}
public static void main(String[] args) {
Son son = new Son();
}
父类写无参构造,子类无参构造,实例化子类,会先调用父类构造方法,再调用子类构造
public class Father {
private String name;
private int age;
public Father() {
System.out.println("父类无参构造");
}
}
public class Son extends Father {
private String name;
private int age;
public Son() {
System.out.println("子类无参构造");
}
}
public static void main(String[] args) {
Son son = new Son();
}
父类没有无参构造,子类必须明确指定调用父类的哪个构造函数,并在子类的构造函数中使用 super 关键字调用。并且super必须在构造函数第一行,否则编译报错
public class Father {
private String name;
private int age;
public Father(String name, int age) {
this.name = name;
this.age = age;
System.out.println("父类有参构造");
}
}