+ 3
Why the class can't be cast ?
class c1 { c1 () { System.out.println ("c1 con"); } static void m () { System.out.println ("m of c1"); } } class c2 extends c1 { c2 () { System.out.println ("c2 con"); } static void m () { System.out.println ("m of c2"); } public static void main(String[] args) { c1 obj=new c1 (); ((c2)obj).m(); } }
5 Réponses
+ 2
Because c2 is a subclass. You can only cast to a superclass.
Suppose we have 2 classes:
class Animal {...}
class Dog extends Animal {...}
If you cast Dog to an Animal, it's ok, because every dog is an animal and it can act like animal.
But if you try to cast an Animal to a Dog, it makes no sense, because not every animal is a dog. It leads to undesirable consequences, for example a cat might start barking.
+ 1
In addition to Stepperwolf's answer:
Sometimes you can downcast your variables to their original types like this:
c1 obj = new c2();
((c2) obj).m();
This anti-pattern can be used when you want to do some specific to type actions in polymorphic system
+ 1
ok thank you guys..just because i ve seen a lesson about downcasting so i tried to do it
+ 1
The Green keep trying
0
Steppenwolf, beautifully said!