子类的 Java 构造函数

标签 java inheritance constructor super mappedsuperclass

我有一个扩展父类(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/

相关文章:

java - 如何在 Windows 7 上运行 Play 框架

java - kafka生产者中的默认分区到底是在哪里决定的?

java - 如何将在终端中运行的 Java 应用程序转换为具有 UI 的桌面应用程序?

c++ - 从模板参数派生的类没有 protected 成员访问

types - 强类型枚举作为 rust 中的联合 : How to determine type of value and retrieve it; How to do "constructors"

C++ 模板对空构造函数的需求

c++ - 抽象类和唯一指针

java - Spring hibernate CRUD : ORA-00923: FROM keyword not found where expected

c++ - 重写 push_back C++

javascript - JavaScript:对象继承自Function.prototype