子类调用构造函数时遇到的小问题
当子类调用构造函数时,若未使用this()和super(),系统则会在子类构造函数时自动调用父类的无参构造函数(即自动补上super()),因此若父类并未构造无参构造函数时,程序就会报错。
public class student extends person{
public student(String name, int age, char sex) {
}
}
class person {
private String name;
private int age;
private char sex;
public person(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
}
解决这个问题的方法如下:
- 在父类中添加无参构造方法 person(){}
- 在子类的构造方法中添加 super( name, age, sex )