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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With