0

私は持っている -

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
}
4

1 に答える 1

6
d.getMethod();

これにより、 b.getAnotherMethod()が内部的に呼び出されます。

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

クラスAのオブジェクトをクラスCにキャストできません

サブクラスオブジェクトスーパークラス参照に割り当てることはできますが、スーパークラスオブジェクトサブクラス参照に割り当てることはできません。この場合は、ユーザーが行います。

于 2012-04-04T06:45:06.483 に答える