我有一个扩展父类(super class)的子类。如果父类(super class)中的构造函数具有参数 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 class)有构造函数也能得到这个?
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);
}
}
最佳答案
构造函数总是做的第一件事就是调用其父类(super class)的构造函数。省略 super
调用并不能规避这一点 - 它只是语法糖,可以让您省去显式指定 super()
(即调用默认构造函数)的麻烦。
您可以做的是将一些默认值传递给父类(super class)的构造函数。例如:
public class SubClass {
private int d;
private int e;
public SubClass(int a, int d, int e) {
super(a, null, null);
this.d = d;
this.e = e;
}
}
关于子类的 Java 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224190/