【问题标题】:Java Constructor of a Subclass子类的 Java 构造函数
【发布时间】: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/…
  • 根据您的需要,您可以使用"" + bString.valueOf(b)int 转换为字符串。

标签: java inheritance constructor super mappedsuperclass


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    如果超类中的构造函数具有参数 a,b,c,例如 MySuperClass(int a, string b, string c)。而子类中的构造函数有参数a,d,e,比如MySubClass(int a, int d, int e),子类的构造函数里面应该放什么?

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

    我可以说 super(a) 这样我就不必复制参数 a 的代码了吗?

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

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

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

    我该如何解决这个问题?

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

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 2018-02-28
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 2014-11-06
      • 1970-01-01
      相关资源
      最近更新 更多