I hava a supeclass called Car with 3 subclasses.
class Ford extends Car{
}
class Chevrolet extends Car{
}
class Audi extends Car{
}
Now i have a function called printMessge(Car car) which will print a message of a particular car type. In the implementation i use if statements to test the instance of the classes like this.
public int printMessge(Car car){
if((Ford)car instanceof Ford){
// print ford
}else if((Chevrolet)car instanceof Chevrolet){
// print chevrolet
}else if((Audi)car instanceof Audi){
// print Audi
}
}
for instance if i call it for the first time with Ford printMessge(new Ford()), it prints the ford message but when i call it with printMessge(new Chevrolet()), i get EXCEPTION from the first if statement that Chevrolet cannot be cast to Ford.
What am i doing wrong and what is the best way.
thanks
You shouldn’t be casting before using
instanceof. The whole point ofinstanceofis to dynamically test it:However, if you’re in control of these classes it would generally be better to make
printMessagean abstract method inCar, so that each subclass can implement it appropriately themselves. Polymorphism via virtual methods is generally preferred over explicit type testing withinstanceof.