Upcasting is allowed in Java, however downcasting gives a compile error.
The compile error can be removed by adding a cast but would anyway break at the runtime.
In this case why Java allows downcasting if it cannot be executed at the runtime?
Is there any practical use for this concept?
public class demo { public static void main(String a[]) { B b = (B) new A(); // compiles with the cast, // but runtime exception - java.lang.ClassCastException } } class A { public void draw() { System.out.println('1'); } public void draw1() { System.out.println('2'); } } class B extends A { public void draw() { System.out.println('3'); } public void draw2() { System.out.println('4'); } }
Downcasting is allowed when there is a possibility that it succeeds at run time:
In some cases this will not succeed:
When a cast (such as this last one) fails at runtime a
ClassCastExceptionwill be thrown.In other cases it will work:
Note that some casts will be disallowed at compile time, because they will never succeed at all: