ClassCastException when trying to cast a subclass

David :

I have this code:

package Maven_test.Maven_project_test;

public class Test {
    class A {
        int i = 10;
    }

    class B extends A {
        int j = 20;
    }

    class C extends B {
        int k = 30;
    }

    public void pruebaJerarquia() {
        A a = new B();
        B b = (B) a;
        C c = (C) b;

        System.out.println(c.k);
    }
}

and I'd like to know why this line:

C c = (C) b;

throws this exception when executing the program:

Exception in thread "main" java.lang.ClassCastException: 
Maven_test.Maven_project_test.Test$B cannot be cast to 
Maven_test.Maven_project_test.Test$C
    at Maven_test.Maven_project_test.Test.pruebaJerarquia(Test.java:21)
    at Maven_test.Maven_project_test.App.main(App.java:10)

I think it has something to do with upcasting and downcasting, but I don't get it. Could it be because "b" is pointing to "a" and with "C c = (C) b" it's like trying to cast something like this?

C c = new A();

Thank you!

Seelenvirtuose :

You are creating one object of type B. As per your class hierarchy, each B object is also an A, but not a C.

Now let's look on how to assign the reference to this B object to various variables:

Object o = new B(); // You can always assign references to an Object-typed variable.
A a = (A) o; // This works because the object is of type A.
B b = (B) o; // This works because the object is of type B.
C c = (C) o; // This does not work because the object is not of type C.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116503&siteId=1