Reputation: 1385
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?
Upvotes: 6
Views: 19724
Reputation: 2019
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
.
Upvotes: 3
Reputation: 7870
Check with instanceof, for example:
car instanceof Audi
This returns true if variable car is an instance of Audi, otherwise returns false.
Upvotes: 2
Reputation: 207006
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?
Upvotes: 8
Reputation: 7771
Obvious or not, this will do the trick:
Car car = cars.get(0);
if(car instanceof Audi) {
Audi audi = (Audi) car;
}
Upvotes: 3