Casting To The Correct Subclass

Posted by kap on Stack Overflow See other posts from Stack Overflow or by kap
Published on 2010-12-25T13:22:17Z Indexed on 2010/12/25 13:54 UTC
Read the original article Hit count: 409

Filed under:

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

© Stack Overflow or respective owner

Related posts about java