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();
}
speak()) on each item which you could declare on the base class and override in the subclass. Then you do not need to worry about the type. If you proceed as you are, then yes, you need to cast to call the method. (I am consciously excluding the option of using reflection to call methods)bark()andfly()to the super classAnimal.