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

I am trying to do this:

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

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

Exception in thread "main" java.lang.ClassCastException: Animals cannot be thrown at Cat on Main.main (Main.java:6)

But in the sample Lern ​​application, Java is displayed just like me.

+5
source share
1 answer

Well, a not an instance of Cat . If you want to drag it into Cat , you need to create Cat (or an instance of some class that extends Cat , of course):

 Animal a = new Cat(); 

Note that if Animal declares makePee() and Cat cancels it, then downcasting is pointless. You can simply call a.makePee() , and the Cat implementation will be used (if you really created Cat , as mentioned above).

+6
source

Source: https://habr.com/ru/post/1261779/


All Articles