所以我遇到的问题是这样的。我编写了一个方法作为程序的一部分,用于显示 ArrayList 中的所有对象。此 ArrayList 中存储了三种不同类型的对象:真菌、花卉和杂草。我可以毫无问题地调用 plantList.get(i).getName()
和 plantList.get(i).getColor
方法。这两个变量都属于称为 Plant 的父类。但是,当调用以下方法 plantList.get(i).getPoison()
(该方法属于 Fungus 子类)时,我收到编译器错误,指出它找不到变量 Fungus。
我已经尝试过使用子类独有的所有其他变量,并且发生了相同的事情。因此,我可以从父类“Plant”访问变量,但不能从“Fungus”、“Flower”或“Weed”的任何子类访问变量。我不熟悉使用子类和父类(super class),所以我很难弄清楚问题到底出在哪里。
public static void displayPlant(ArrayList<Plant> plantList) {
for (int i = 0; i < plantList.size(); i++) {
System.out.print(plantList.get(i).getName());
System.out.print(plantList.get(i).getID());
System.out.print(plantList.get(i).getColor());
if (plantList.get(i).contains(Fungus) == true) {
System.out.print(plantList.get(i).getPoison());
}
else if (plantList.get(i).contains(Flower) == true) {
System.out.print(plantList.get(i).getSmell());
System.out.print(plantList.get(i).getThorns());
}
else {
System.out.print(plantList.get(i).getPoison());
System.out.print(plantList.get(i).getEdible());
System.out.print(plantList.get(i).getMedicinal());
}
}
}
最佳答案
一个好的解决方案是使用动态调度。 IE。让元素自己决定要打印什么信息。
class Plant {
...
public String toString() {
return String.join(" ", getName(), getID(), getColor());
}
}
class Fungus extends Plant {
...
@Override
public String toString() {
return String.join(" ", super.toString(), getPoison());
}
}
class Flower extends Plant {
...
@Override
public String toString() {
return String.join(" ", super.toString(), getSmell(), getThorns());
}
}
class Weed extends Plant {
...
@Override
public String toString() {
return String.join(" ", super.toString(), getPoison(), getEdible(), getMedicinal());
}
}
你的循环将如下所示:
public static void displayPlant(ArrayList<Plant> plantList) {
for(Plant p : plantList)
System.out.println(p); // This calls toString
}
关于java - 只能从方法访问父类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622098/