So the issue I'm running into is this. I've written a method as a part of a program that I'm using to display all the objects in an ArrayList. There are three different types of objects stored in this ArrayList: Fungus, Flowers and Weeds. I'm able to call plantList.get(i).getName()
and plantList.get(i).getColor
methods with no issue. Both of these variables belong to the parent class called Plant. However, when calling the following method plantList.get(i).getPoison()
(this method belongs to the subclass Fungus) I get a compiler error saying that it cannot find the variable Fungus.
I've tried it with every other variable unique to a subclass, and the same things happens. So I can access variables from the parent class 'Plant' but not from any of the subclasses of 'Fungus' 'Flower' or 'Weed'. I'm new to using subclasses and superclasses so I'm having a hard time figuring out exactly where the issue is arising.
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());
}
}
}
Java is strongly typed language. That means that, if you want to use methods of child class you have to cast down to child class.
In your example:
...
else if (plantList.get(i) instanceof Fungus) { //check if plant is fungus
System.out.print(plantList.get(i).getSmell());
System.out.print(((Fungus)plantList.get(i)).getThorns()); //downcasting
}
...
Your check using constains
wouldn't work. To check type of object you need to use operator instanceof
.