【问题标题】:Inheriting constructors from superclass?从超类继承构造函数?
【发布时间】:2017-02-17 14:59:22
【问题描述】:

我有一个名为 Robot.java 的类:

class Robot {
String name;
int numLegs;
float powerLevel;

Robot(String productName) {
    name = productName;
    numLegs = 2;
    powerLevel = 2.0f;
}

void talk(String phrase) {
    if (powerLevel >= 1.0f) {
        System.out.println(name + " says " + phrase);
        powerLevel -= 1.0f;
    }
    else {
        System.out.println(name + " is too weak to talk.");
    }
}

void charge(float amount) {
    System.out.println(name + " charges.");
    powerLevel += amount;
}
}

还有一个名为 TranslationRobot.java 的子类:

public class TranslationRobot extends Robot {
    // class has everything that Robot has implicitly
    String substitute; // and more features

    TranslationRobot(String substitute) {
        this.substitute = substitute;
    }

    void translate(String phrase) {
        this.talk(phrase.replaceAll("a", substitute));
    }

    @Override
    void charge(float amount) { //overriding
        System.out.println(name + " charges double.");
        powerLevel = powerLevel + 2 * amount;
    }
}

当我编译 TranslationRobot.java 时,出现以下错误:

TranslationRobot.java:5: error: constructor Robot in class Robot cannot be applied to given types;
TranslationRobot(String substitute) {
                                    ^
required: String
found: no arguments
reason: actual and formal argument lists differ in length

我知道这是指从超类继承的东西,但我真的不明白问题是什么。

【问题讨论】:

  • 构造函数不会被继承。

标签: java class oop object


【解决方案1】:

这是因为子类在构造时总是需要调用其父类的构造函数。如果父类有一个无参数的构造函数,这会自动发生。但是你的Robot 类只有一个构造函数,它接受String,所以你需要显式调用它。这可以通过 super 关键字来完成。

TranslationRobot(String substitute) {
    super("YourProductName");
    this.substitute = substitute;
}

或者,如果您想给每个 TranslationRobot 一个唯一的产品名称,您可以在构造函数中使用一个额外的参数并使用它:

TranslationRobot(String substitute, String productName) {
    super(productName);
    this.substitute = substitute;
}

【讨论】:

  • 太棒了,谢谢,只要它是一个字符串,我在 super 方法中放什么有关系吗?我可以写 Robot.name 吗?
  • @user6731064 你可以放任何你想要的东西(只要它是一个字符串),但是this.name - 我认为这就是你的意思 - 不会做你想要的。请记住,name 还没有值。这就是构造函数的用途。我的猜测是你想要的是让TranslationRobot 在它的构造函数中使用两个Strings,并使用其中一个作为super 的参数。
猜你喜欢
  • 2018-06-06
  • 2011-01-20
  • 1970-01-01
  • 2012-09-03
  • 2012-10-16
  • 2014-09-02
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多