Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.9k points)

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");

  }

}

1 Answer

0 votes
by (46k points)

Using your example, you could do:

public void doit(A a) {

    if(a instanceof B) {

        // needs to cast to B to access draw2 which isn't present in A

        // note that this is probably not a good OO-design, but that would

        // be out-of-scope for this discussion :)

        ((B)a).draw2();

    }

    a.draw();

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 7, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)

Browse Categories

...