6

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?

user3339562
  • 1,325
  • 4
  • 18
  • 34
  • You can use instanceof, but that subverts OOP principles. What are you trying to do? – Adrian Leonhard Feb 19 '15 at 21:57
  • "*how can I find out which one is Audi, which one is Seat*" why do you even want to do it? Doesn't your `Car` class have already all method you need from car? – Pshemo Feb 19 '15 at 22:00
  • @AdrianLeonhard, I am trying to get the data for specific car from a list of cars. I am receiving that list from another place and need to process it. – user3339562 Feb 19 '15 at 22:00
  • @Pshemo, no. Each specific car has some extra variables with it's getters and setters. – user3339562 Feb 19 '15 at 22:00
  • OK, in that case `instanceof` is operator you are looking for. But still I am interested what data could have `Seat` which `Audi` or other cars shouldn't have. – Pshemo Feb 19 '15 at 22:02

4 Answers4

8

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?

Community
  • 1
  • 1
Jesper
  • 202,709
  • 46
  • 318
  • 350
3

Obvious or not, this will do the trick:

Car car = cars.get(0);
if(car instanceof Audi) {
  Audi audi = (Audi) car;
}
Tobias
  • 7,723
  • 1
  • 27
  • 44
3

You can use instanceof before casting. For example:

Car someCar = cars.get(0);
Audi audi = null;
if(someCar instanceof Audi){
audi = (Audi) someCar;
}
if(audi != null){
//...

But likely it's a bad idea, because generics was introduced to avoid using casting and instanceof.

Dmytro
  • 1,850
  • 3
  • 14
  • 20
2

Check with instanceof, for example:

car instanceof Audi

This returns true if variable car is an instance of Audi, otherwise returns false.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54