+ 1
downcasting in Java
public class Down{ public void method(){ System.out.println("1"); } } class Try extends Down{ public void method(){ System.out.println("2"); } } // in main public static void main(String[] args) { Down e = new Down(); ((Try)e).method(); } when I run this code, there's no problem compiling, but an exception: "Exception in thread "main" java.lang.ClassCastException: Down cannot be cast to Try" it is supposed to output "2", isn't it? Why it cannot be cast?
2 Answers
+ 10
Parent object cannot be casted into child object this way. Because child objects usually have more properties than parent.
You may write:
Down e = new Try();
https://code.sololearn.com/cKrNOy8i8OoC/?ref=app
+ 1
I see...
but in SoloLearn's Java course, the chapter about downcasting (More on Classes -> Downcasting), the code in main is the same as what i have posted, I cannot post a screen shot here but the code in the course was:
1 Animal a = new Animal();
2 ((Cat)a).makeSound();
here in the first line the class on each side of "=" is the same, so is the course wrong?