为什么我在这里得到ClassCastException?

时间:2016-06-10 15:42:05

标签: java inheritance polymorphism

为什么不能将o1(C1是C3的超类)转换为C3(C1的子类)?

interface I1 { }
interface I2 { }
static class C1 implements I1 { }
static class C2 implements I2 { }
static class C3 extends C1 implements I2 { }
static class C5 extends  C1 implements  I2 {}




public static void main(String[] args) {
    C1 o1 = new C1();
    C2 o2 = new C2();
    C3 o3 = new C3();
    C5 o5 = new C5();
    o3 = (C3) o1;
}

1 个答案:

答案 0 :(得分:2)

每个C3都是C1,但不是每个C1都是C3。您正在尝试将C1的实例转换为C3

从文档中查看此示例

Object x = new Integer(0);
System.out.println((String)x);