2017-02-17 16 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あなたは何でも(Stringである限り)好きなものを置くことができますが、 'this.name'はあなたが意味するものだと思います。あなたが望むことはしません。 'name'にはまだ価値がないことに注意してください。それがコンストラクターのためのものです。私の推測では、あなたが望むのは、 'TranslationRobot'がコンストラクタに2つの' String'を取り、それらのうちの1つを 'super'の引数として使うことです。 – resueman

関連する問題