我正在編寫演示繼承使用的程序,並且我使用super()關鍵字創建了一個變量。我現在試圖將該變量的值放入一個調用它的新方法中,以便我可以在我的main方法中調用該方法以在其他類中使用它的值。如何返回超級變量的值?
下面是相關代碼:
食品類(超類)
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
肉類(super關鍵字子類)
public class Meat extends Food
{
public Meat() {
super("Meat");
}
public String getName() {
return //get super() value??;
}
}
主類
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
Meat meatExample = new Meat();
System.out.println("************Wolf\"************");
System.out.println("Wolves eat " + meatExample.getName());
}
}
任何幫助表示讚賞,謝謝。
爲什麼當繼承的實現工作正常時,你會重寫'getName'? – user2357112
我知道你的問題是繼承的誤解http://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html – litelite