ClassCastException冒险

时间:2012-04-04 06:42:24

标签: java classcastexception

我有 -

class A {
    // contains certain set() and get() methods
}

class B extends A {
    public A getAotherMethod() {
      A a = new A();
      // Contains some logic
      return a
      }
}

class C extends B {
    // contains certain set() and get() methods
}

class D {
    public Object getMethod() {

      B b = new B();
      // Contains some logic
      return b.getAnotherMethod()
     }
}


public static void main(String[] args) {
    A a = new A();
    B b = new B();
    C c = new C();
    D d = new D();
    c = (C) d.getMethod(); // This is giving me ClassCastException
}

1 个答案:

答案 0 :(得分:6)

d.getMethod();

这将在内部调用 b.getAnotherMethod(),其中

A a = new A();
// Contains some logic
return a

A类的对象无法转换为 C类

我们可以将子类对象分配给超类引用但是我们不能将超类对象分配给子类引用什么是在这种情况下由你完成。