[英]Java - Return field value of class that extends the super class
當我創建“ Sword”的實例並調用getName()時,會收到null。 我該如何做,以使Weapon類中的getName()返回在Weapon中設置的任何“名稱”。
public abstract class Weapon extends items.Item {
public String name;
public int damage;
public ItemType itemType = ItemType.Weapon;
public String getName(){
return name;
}
}
public class Sword extends Weapon{
int damage = 10;
int manaCost = 0;
String name = "Steel Sword";
}
您在Sword
name
變量與在Weapon
變量不同-它在Sword
隱藏了一個。 當您擁有Weapon
類型的變量時,訪問名稱將訪問未初始化的Weapon
name
,因此它保持為null
。
您可以在Sword
中創建一個構造函數,以將現有的name
變量設置為所需的name
,而不用聲明新變量。
您可以將構造函數添加到Weapon
類中,以便其所有子類都必須使用它來初始化該類的正確數據
public abstract class Weapon {
public String name;
public int damage;
public ItemType itemType = ItemType.Weapon;
public Weapon(String name, int damage) {//Constructor for creating a weapon to be used by subclasses
this.name = name;
this.damage = damage;
}
}
然后創建一個Sword
名為“亮劍”和10損害你只需調用它的超構造是這樣的:
public class Sword extends Weapon {
public Sword() {
super("Sword", 10); //Calls the constructor from the Weapon class with the values "Sword" and 10
}
}
我認為這是更可取的解決方案,因為如果Sword
不調用武器的構造函數,它將引起編譯時警告,並且它將確保正確初始化所有字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.