Java: getting a subclass from a superclass list

I am new to 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 a way to get either a Dog or Cat instance from the Aminal list? 2) If yes, how to build getCertainAnimals method correctly?

+6
source share
2 answers
 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 be compiled if you are not using instanceof , but it will also allow you to drop a to Cat or Dog , even if a is Rat . Despite compilation, you will get a ClassCastException at runtime. So make sure you use instanceof .

+4
source

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 the Animal class and compare it with Animal subclasses. 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 output as

 Animal is a Dog Animal is a Cat 

Basically, both do the same thing. Just to better understand.

+2
source

Source: https://habr.com/ru/post/949961/


All Articles