by BehindJava

What Down casting in Java

Home » java » What Down casting in Java

In this tutorial, we are going to learn about down casting in detail.

Downcasting in Java

In Java, up-casting is permitted, while down-casting results in a build error.

  • Although adding a cast can fix the compilation error, the programme will still break at runtime.
  • Why does Java permit down-asting in this situation if runtime execution is not possible?

    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”); } }

* We can all see that your offered code won't execute at runtime. This is so that we can understand that new A() can never be an object of type B.
The compiler, however, does not see it that way. The compiler only notices this by the time it is determining whether the cast is permitted:
```java
variable_of_type_B = (B)expression_of_type_A;
  • And as other people have shown, that kind of cast is completely lawful. The right-hand phrase might very well evaluate to a B object. With the “expression” view of the code, the cast may succeed because the compiler recognizes that A and B share a subtype relationship.
  • When the compiler is certain of the exact object type expression of type A will have, it does not take this unique case into account. It only recognizes A as the static type and assumes that A or any A ancestor, including B, might be the dynamic type.

Note: In Java, up-casting is permitted, while down-casting results in a build error. Although adding a cast can fix the compilation error, the programme will still break at runtime. This is so that we can understand that new A() can never be an object of type B.