sir*_*omz 21 java constructor class superclass
我正在处理一个项目,我收到错误"隐式超级构造函数Person()未定义.必须显式调用另一个构造函数",我不太明白.
这是我的人类:
public class Person {
public Person(String name, double DOB){
}
}
Run Code Online (Sandbox Code Playgroud)
我的学生班在尝试实现person类时,并给它一个教师变量.
public class Student extends Person {
public Student(String Instructor) {
}
}
Run Code Online (Sandbox Code Playgroud)
pxm*_*pxm 34
如果构造函数未显式调用超类构造函数,则Java编译器会自动插入对超类的无参数构造函数的调用.
如果超类没有无参数构造函数,则会出现编译时错误.对象确实有这样的构造函数,因此如果Object是唯一的超类,则没有问题.
参考:http://docs.oracle.com/javase/tutorial/java/IandI/super.html :(参见"SubClass Constructors"部分)
因此,每当处理参数化构造函数时,都会 super(parameter1, parameter2 ..)调用父构造函数.
此super()调用也应该是构造函数块中的FIRST行.
您需要super调用已定义的构造函数:
public Student(String instructor) {
super(/* name */, /* date of birth */);
}
Run Code Online (Sandbox Code Playgroud)
你不能只是调用super()因为没有定义构造函数.
这就是我实现它的方式(在我的例子中,超类是 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);
}
}
Run Code Online (Sandbox Code Playgroud)