子类的Java构造函数

时间:2016-10-24 17:30:55

标签: java inheritance constructor super mappedsuperclass

我有一个扩展超类的子类。如果超类中的构造函数具有参数 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"中没有默认构造函数。为什么我得到这个,即使超类有一个构造函数?

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);
    }
}

2 个答案:

答案 0 :(得分:2)

构造函数总是做的第一件事是调用它的超类'构造函数。省略super调用并不能避免这种情况 - 它只是语法糖,可以省去明确指定super()(即调用默认构造函数)的麻烦。

您可以做的是将一些默认值传递给超类的构造函数。 E.g:

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;
    }
}

答案 1 :(得分:1)

  

如果超类中的构造函数具有参数a,b,c,如MySuperClass(int a,string b,string c)。并且子类中的构造函数具有参数a,d,e,如MySubClass(int a,int d,int e),应该在子类的构造函数内部进行什么?

您是唯一做出此决定的人,因为这取决于数字对您的商业案例的意义。只要它们只是没有任何语义含义的数字就没关系。

  

我可以说super(a)所以我不必复制参数a的代码吗?

不,您必须指定应将哪些类的构造函数参数或常量传递给超类的构造函数。再次没有“自动”解决方案。作为程序员,您有责任决定将哪些值传递给超类构造函数以及它们来自何处。

  

为什么我会得到这个,即使超类有一个构造函数?

超类构造函数不是默认构造函数(没有参数)。

  

我该如何解决这个问题?

再一次,这没有一般性答案。通常唯一有效的方法是提供传递给超类构造函数的值。在极少数情况下,可能适合创建其他默认构造函数。