子类调用构造函数时遇到的小问题

子类调用构造函数时遇到的小问题

当子类调用构造函数时,若未使用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;
    }
}

错误信息01
错误信息02

解决这个问题的方法如下:

  • 在父类中添加无参构造方法 person(){}
  • 在子类的构造方法中添加 super( name, age, sex )
文章作者: 刘山
文章链接: http://threee-hub.github.io/2019/11/09/%E5%AD%90%E7%B1%BB%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 刘山的博客