+ 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(); } }

1st Aug 2018, 5:21 PM
De Vinci
5 Answers
+ 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.
1st Aug 2018, 6:30 PM
Steppenwolf
Steppenwolf - avatar
+ 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
1st Aug 2018, 7:04 PM
Mishin870
Mishin870 - avatar
+ 1
ok thank you guys..just because i ve seen a lesson about downcasting so i tried to do it
1st Aug 2018, 7:19 PM
De Vinci
+ 1
The Green keep trying
1st Aug 2018, 7:24 PM
Steppenwolf
Steppenwolf - avatar
0
Steppenwolf, beautifully said!
2nd Feb 2019, 2:48 PM
Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠœŠ°Š¹Š“урŠ¾Š²
Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠœŠ°Š¹Š“урŠ¾Š² - avatar