I have a question about Parametric Polymorphism. How do I determine the actual type and avoid casting If I have a collection with a mix of child types. For example
class Animal{
}
class Bird extends Animal{
void fly(){}
}
class Dog extends Animal{
void bark(){}
}
ArrayList<Animal> list = new ArrayList<Animal>();
The problem is how do I know which one is which when I iterating through the Animal collection. Do I need to use instanceof to check the actual type every time?
for(Animal animal : list){
if(animal instanceof Dog){
((Dog) animal).bark();
}
else ((Bird) animal).fly();
}
If you need to do this, that means that’s a common action. You usually would have this :
and in your loop you would simply call the
actmethod :