Java: Getting the subclass from a superclass list
java, subclass, superclass
Solution
Animal a = animals.get(i);
if (a instanceof Cat)
{
Cat c = (Cat) a;
}
else if (a instanceof Dog)
{
Dog d = (Dog) a;
}
NB: It will compile if you do not use `instanceof`, but it will also allow you to cast `a` to `Cat` or `Dog`, even if the `a` is a `Rat`. Despite compiling, you will get a `ClassCastException` on runtime. So, make sure you use `instanceof`.
Problem
i'm new with java and have 2 questions about the following code: ``` class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Rat extends Animal { } class Main { List<Animal> animals = new ArrayList<Animal>(); public void main(String[] args) { animals.add(new Dog()); animals.add(new Rat()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Rat()); animals.add(new Cat()); List<Animal> cats = getCertainAnimals( /*some parameter specifying that i want only the cat instances*/ ); } } ``` 1) Is there any way to get either the Dog or Cat instances from the Aminal list? 2) If yes, how should i correctly build the getCertainAnimals method?