我正在编写演示继承使用的程序,并且我使用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