Java – polymorphism, ArrayList and objects
This is a common problem I try to understand the concept of polymorphism when creating a valid program or at least one working program
The program will add, delete, search and display plants
Suppose I have to create a super plant and three different plants (flowers, fungi, weeds) extending from the plant
Question: I want to be able to create a factory ArrayList or array Is that possible? Or what is the most logical thing?
The above code is just to illustrate my point There is no right way
class Plant{ //atributes //constructor //setters and getters } class Flower extends Plant{ //with some different attributes } class Fungus extends Plant{ //with some different attributes } class Weed extends Plant{ // with some different attributes } public class PlantList{ public static void main(String[] args){ //HERE is where I'm confused ArrayList<Plant> plantList= new ArrayList<Plant>(); // OR Plant plantList= new Plant[25]; plantList[0] = new Flower(); plantList[1] = new weed(); plantList[2] = new fungus(); //or completely way off? //add() //remove () //search() //display() }
Can someone explain how I can add different types of plants to the array or ArrayList?
Solution
By default, you can put any object into the list, but starting with Java 5, Java genetics can limit the types of objects that can be inserted into the list
List<Plant> list = new ArrayList<Plant>();
This list can only insert plant instances now This is polymorphism between arrays
An annoying aspect of this topic is that although flower is a subtype of plant, this does not mean that ArrayList < flower > is a subtype of ArrayList < plant >
What you can do is
List<Plant> list = new ArrayList<Plant>();
then
Plant flower1 = new Flower(); Plant weed1 = new Weed(); list.add(flower1); list.add(weed1);
The key point of generics is to add compile - time type security, which is why the second method is not type - safe