Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java downcasting) What did I do wrong in this example?

I try to downcast in this way:

public static void main(String[] args){
    Animal a = new Animal();
    ((Cat)a).makePee();
}

Cat extends Animal and both have the same Method makePee(). If I try to run this, The compiler shows me an error message:

Exception in thread "main" java.lang.ClassCastException: Animal cannot be cast to Cat at Main.main(Main.java:6)

But in the Example of the App Lern Java is shown really the same as I do.

like image 753
Abraham Josef Avatar asked Dec 23 '16 12:12

Abraham Josef


1 Answers

Well, a isn't an instance of a Cat. If you want to downcast it to a Cat, you need to actually create a Cat (or an instance of some class that extends Cat, of course):

Animal a = new Cat();

Note, however, that if Animal declares makePee() and Cat overrides it, the downcasting is pointless. You can just call a.makePee(), and Cat's implementation would be used (provided you actually created a Cat, as noted above).

like image 50
Mureinik Avatar answered Oct 30 '22 23:10

Mureinik