2017-02-17 141 views
2

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

构造函数不能被继承。 – Kayaman

回答

4

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

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

或者,如果你想给每个TranslationRobot独特的产品名称,你可能需要一个额外的参数的构造函数和使用:

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

真棒谢谢,只要它是一个字符串,我把它放在超级方法里面吗?我可以写Robot.name吗? – user6731064

+0

@ user6731064你可以放任何你想要的东西(只要它是一个字符串),但是'this.name' - 我认为是你的意思 - 不会做你想要的。记住'name'还没有价值。这就是构造函数的用途。我的猜测是,你想要的是让'TranslateRobot'在它的构造器中带两个'String',并将其中的一个用作'super'的参数。 – resueman