简体   繁体   中英

(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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM