Home > Enterprise >  Multiple casting in Java
Multiple casting in Java

Time:06-14

I know some rules around how Java performs the casting but I am unable to figure out the rules in the following example:

interface I {}
class A implements I {}
class B extends A {}
class C extends B {}

class DriverClass {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();

        a = (A)(B)(C)c;   // line 1 - Valid
        a = (A)(C)(B)c;   // line 2 - Valid
        a = (B)(A)(C)c;   // line 3 - Valid
        a = (B)(C)(A)b;   // line 4 - Runtime error
        a = (C)(B)(A)b;   // line 5 - Runtime error
        a = (C)b;         // line 6 - Runtime error
    }
}

Can someone please explain why line 1 to line 3 are valid statements whereas line 4 to line 6 throw Runtime Error of ClassCastException?

CodePudding user response:

Your class declaration says that every C is a B and every B (including the C's) is an A.

Now you make c reference a new C, so it's also a B and an A. That means you can cast c to any of the three classes, in any order, and there won't be an error.

Then you make b reference a new B, that's not a C. That means you can cast it to A or B without any problems, but as soon as you try to cast b to C, you get an error, because the object referenced by b is not a C.

  • Related