Check if parent class is instance of child class

java

Solution

You can use `instanceof`:

Car car = cars.get(0);
if (car instanceof Audi) {
    // It's an Audi, now you can safely cast it
    Audi audi = (Audi) car;
    // ...do whatever needs to be done with the Audi
}

However, in practice you should use `instanceof` sparingly - it goes against object oriented programming principles. See, for example: Is This Use of the "instanceof" Operator Considered Bad Design?

Problem

I have one class defined like this: ``` class Car { } ``` And many other defined like this: ``` class Audi extends Car { } class Seat extends Car { } class Mercedes extends Car { } class Opel extends Car { } ... ``` I have a situation where I receive a list of all these cars which is defined like this: ``` List<Car> cars = new ArrayList<Car>(); ``` In that list there are many different cars so how can I find out which one is Audi, which one is Seat etc? I've tried to do this for cars for which I know they are of type Audi: ``` Audi audi = (Audi) cars.get(0); ``` This throws `ClassCastException`. How to handle this situation?

Original source

Related problems