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

时间:2014-04-30 18:31:16

标签: java class constructor superclass

我正在处理一个项目,我收到错误“隐式超级构造函数Person()未定义。必须显式调用另一个构造函数”,我不太明白。

这是我的人类:

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

    }
}

我的学生班在尝试实施人员课程时,并给它一个教师变量。

public class Student extends Person {

    public Student(String Instructor) {

    }

}

5 个答案:

答案 0 :(得分:28)

  

如果构造函数没有显式调用超类构造函数,   Java编译器自动插入对无参数的调用   超类的构造函数。

     

如果超级班没有   无参数构造函数,您将得到编译时错误。宾语   确实有这样的构造函数,所以如果Object是唯一的超类,   没问题。

参考:http://docs.oracle.com/javase/tutorial/java/IandI/super.html: (参见“SubClass Constructors”一节)

因此,每当处理参数化构造函数时,都会对父构造函数进行super(parameter1, parameter2 ..)调用。 此super()调用也应该是构造函数块中的FIRST行。

答案 1 :(得分:6)

您需要对定义的构造函数进行super调用:

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

您不能只调用super(),因为没有定义构造函数。

答案 2 :(得分:1)

这就是我实现它的方式(在我的例子中,超类是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);
    }
}

答案 3 :(得分:0)

在创建子类构造函数时,如果没有使用super显式调用超类构造函数,那么Java将插入对no-arg“default”超类构造函数的隐式调用,即super();

但是,您的超类Person没有no-arg构造函数。在Person中提供显式的无参数构造函数,或者在Student构造函数中显式调用现有的超类构造函数。

答案 4 :(得分:0)

您无法在不调用其超类的构造函数的情况下创建实例。并且jvm不知道如何从Student(String)构造函数调用Person(String,double)。

相关问题