【发布时间】:2016-10-24 17:30:54
【问题描述】:
我有一个子类扩展了一个超类。如果超类中的构造函数有参数 a,b,c 如MySuperClass(int a, string b, string c)。而子类中的构造函数有参数a,d,e如MySubClass(int a, int d, int e),子类的构造函数里面应该放什么?我可以说super(a),这样我就不必复制参数a的代码了吗?但是 super 的构造函数有 3 个参数;所以我想我不能那样做。
另外,如果我只是忽略使用 super 并将字段分配给参数(如 this.fieldName=parameterName),我会收到“super 中没有默认构造函数”的错误,为什么即使 super 类有一个构造函数?
public abstract class Question {
// The maximum mark that a user can get for a right answer to this question.
protected double maxMark;
// The question string for the question.
protected String questionString;
// REQUIRES: maxMark must be >=0
// EFFECTS: constructs a question with given maximum mark and question statement
public Question(double maxMark, String questionString) {
assert (maxMark > 0);
this.maxMark = maxMark;
this.questionString = questionString;
}
}
public class MultiplicationQuestion extends Question{
// constructor
// REQUIRES: maxMark >= 0
// EFFECTS: constructs a multiplication question with the given maximum
// mark and the factors of the multiplication.
public MultiplicationQuestion(double maxMark, int factor1, int factor2){
super(maxMark);
}
}
【问题讨论】:
-
你能添加你的代码吗?
-
这个答案将帮助您对构造函数进行建模stackoverflow.com/questions/9586367/…
-
根据您的需要,您可以使用
"" + b或String.valueOf(b)将int转换为字符串。
标签: java inheritance constructor super mappedsuperclass