Reputation: 187
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?
Upvotes: 7
Views: 3853
Reputation: 68985
You can do something like the following
List<Animal> animalList = new ArrayList<Animal>();
animalList.add(new Dog());
animalList.add(new Cat());
for(Animal animal : animalList) {
if(animal instanceof Dog) {
System.out.println("Animal is a Dog");
}
else if(animal instanceof Cat) {;
System.out.println("Animal is a Cat");
}
else {
System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
}
}
You can also check for the class of the Animal and compare it with Animal sub classes. As in
for(Animal animal : animalList) {
if(animal.getClass().equals(Dog.class)) {
System.out.println("Animal is a Dog");
}
else if(animal.getClass().equals(Cat.class)) {;
System.out.println("Animal is a Cat");
}
else {
System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
}
}
In both cases you will get the outputs as
Animal is a Dog
Animal is a Cat
Basically both do the same thing. Just to give you better understanding.
Upvotes: 2
Reputation: 14709
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
.
Upvotes: 4