I have a question about the application of polymorphism: let's say I have a Bird class, and I have many classes that extend it (for example, Pigeon , Falcon , etc.). Then I have a Cage class. In this class, I want to make a list of birds that live in this cage (only one bird can live in each cage).
Because of this, I donβt know the extended list type (A Pigeon ? Or maybe Eagle ?), The only thing I know is that it will be 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 can't I initialize something like this in the constructor: [...]
private List<Bird> birdList; public Cage() { this.birdList = new ArrayList<Pigeon>(); }
If you cannot do this, is it possible to achieve my goal differently?
source share