2017-02-17 138 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