为什么不能将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;
}
答案 0 :(得分:2)
每个C3都是C1,但不是每个C1都是C3。您正在尝试将C1
的实例转换为C3
。
从文档中查看此示例
Object x = new Integer(0);
System.out.println((String)x);