从超类继承构造函数?

时间:2017-02-17 14:59:22

标签: java class oop object

我有一个名为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

我知道这是指从超类中继承的内容,但我并不能真正理解问题所在。

1 个答案:

答案 0 :(得分:4)

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

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

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

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