Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if parent class is instance of child class

Tags:

java

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?

like image 399
user3339562 Avatar asked Feb 19 '15 21:02

user3339562


2 Answers

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?

like image 146
Jesper Avatar answered Sep 28 '22 17:09

Jesper


Obvious or not, this will do the trick:

Car car = cars.get(0);
if(car instanceof Audi) {
  Audi audi = (Audi) car;
}
like image 39
Tobias Avatar answered Sep 28 '22 17:09

Tobias