Casting To The Correct Subclass
- by kap
Hi Guys
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