我正在编写演示继承使用的程序,并且我使用 super() 关键字创建了一个变量。我现在试图将该变量的值放入一个调用它的新方法中,以便我可以在主方法中调用该方法以在其他类中使用它的值。
这是相关的代码:
食品班(超班)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
肉类类(带有 super 关键字的子类)
public class Meat extends Food
{
public Meat() {
super("Meat");
}
public String getName() {
return //get super() value??;
}
}
Run Code Online (Sandbox Code Playgroud)
主班
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());
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏,谢谢。
你可以做
public String getName() {
return super.getName();
}
Run Code Online (Sandbox Code Playgroud)
尽管您甚至不需要首先覆盖该方法,因为您在类中声明了字段名称,这意味着它可以从任何地方访问。superpublic
| 归档时间: |
|
| 查看次数: |
6768 次 |
| 最近记录: |