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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With