隐式超级构造函数Person()未定义。必须显式调用另一个构造函数?

45

我正在开展一个项目,但是遇到了错误信息“implicit super constructor Person() is undefined. Must explicitly invoke another constructor”,我不太理解它的含义。

这是我的Person类:

public class Person {
    public Person(String name, double DOB){

    }
}

当我的学生课程尝试实现person类并赋予其一个instructor变量时。

public class Student extends Person {

    public Student(String Instructor) {

    }

}

4
public Student(String instructor) 的第一行尝试使用 super("Name", dob); - Faisal Ali
如果您不调用适当的超级构造函数,学生如何知道自己的姓名和出生日期? - Richard Tingle
6个回答

67
如果一个构造函数没有显式地调用超类构造函数,则Java编译器会自动插入对超类无参构造函数的调用。
如果超类没有无参构造函数,则会出现编译时错误。Object有这样的构造函数,所以如果Object是唯一的超类,则没有问题。
参考:http://docs.oracle.com/javase/tutorial/java/IandI/super.html : (请参见“子类构造函数”部分)
因此,在处理参数化构造函数时,应该调用父构造函数super(parameter1, parameter2 ..)此外,这个super()调用应该是你构造器块的第一行。 否则,如果情况需要,请在父类中创建额外的无参构造函数。

12

你需要在已定义的构造函数中进行super调用:

public Student(String instructor) {
    super(/* name */, /* date of birth */);
}

你不能直接调用super(),因为该构造函数未定义。


7
这是我实现它的方法(在我的情况下,超类是Team,子类是Scorer):
// Team.java
public class Team {
    String team;
    int won;
    int drawn;
    int lost;
    int goalsFor;
    int goalsAgainst;
    Team(String team, int won, int drawn, int lost, int goalsFor, int goalsAgainst){
        this.team = team;
        this.won = won;
        this.drawn = drawn;
        this.lost = lost;
        this.goalsFor = goalsFor;
        this.goalsAgainst = goalsAgainst;
    }
    int matchesPlayed(){
        return won + drawn + lost;
    }
    int goalDifference(){
        return goalsFor - goalsAgainst;
    }
    int points(){
        return (won * 3) + (drawn * 1);
    }
}
// Scorer.java
public class Scorer extends Team{
    String player;
    int goalsScored;
    Scorer(String player, int goalsScored, String team, int won, int drawn, int lost, int goalsFor, int goalsAgainst){
        super(team, won, drawn, lost, goalsFor, goalsAgainst);
        this.player = player;
        this.goalsScored = goalsScored;
    }
    float contribution(){
        return (float)this.goalsScored / (float)this.goalsFor;
    }
    float goalsPerMatch(){
        return (float)this.goalsScored/(float)(this.won + this.drawn + this.lost);
    }
}

2
创建子类构造函数时,如果您没有使用super显式调用超类构造函数,则Java将插入对无参“默认”超类构造函数的隐式调用,即super();
但是,您的超类Person没有无参构造函数。请在Person中提供一个明确的无参构造函数,或在Student构造函数中显式调用现有的超类构造函数。

0
一个解决这个问题的简单方法是你可以在超类中实例化一个无参数构造函数。

0

如果你不调用其父类的构造函数,就无法创建实例。而且 JVM 不知道如何从你的 Student(String) 构造函数中调用 Person(String, double)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接