I have a question on applying polymorphism: Let's assume I have a class Bird
, and I have many classes that extend it (like Pigeon
, Falcon
and so on).
Next, I have a Cage
class. In this class, I want to make a list of birds which live in that cage (only one kind of bird can live in each cage).
Because of that, I do not know the extended type of the list (A Pigeon
? Or maybe an Eagle
?), the only thing i know is that it will be a Bird
.
If Pigeon extends Bird
Using polymorphism I can declare a bird as:
Bird tom = new Pigeon();
instead of Pigeon tom = new Pigeon();
So why I can't initialize something like that in the constructor: [...]
private List<Bird> birdList;
public Cage() {
this.birdList = new ArrayList<Pigeon>();
/* Instead of birdList = new ArrayList<Bird>(); */
}
If you cannot do that, is it possible to achieve my goal in another way?