Polymorphism, ArrayList, and Objects

This is a bit of a general question. I am trying to understand the concept of polymorphism while creating an efficient program or at least a working program.

The program will add, remove, search and display the plants.

Let’s say I have to create a super class plant and three different plants (flowers, fungus, weed) to extend from plant.

QUESTION: I want to be able to create a plant ArrayList or Array. Is that possible? or what would be the most logical thing to do?

The code above is merely to get my point across. Not by any means correct.

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 me how to add the tree different types of plants to an Array or ArrayList ?

Answer

By default you can put any Object into a List, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a List.

List<Plant> list = new ArrayList<Plant>();

This List can now only have Plant instances inserted into it. And this is polymorphism between arrays.

One annoying aspect regarding this topic is that although Flower is a subtype of Plant, that doesn’t 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 point of Generics is to add the compile time type safety, so that kind of answers why the second approach is not type safety.

Leave a Reply

Your email address will not be published. Required fields are marked *