2012-04-04 115 views
0

我有 -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 
} 
+0

“我有一辆汽车,当我开车撞墙时,它会打破。” – Ingo 2013-07-25 10:27:08

回答

6
d.getMethod(); 

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

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

类的对象的无法投射到C级

我们可以指定子类对象超类引用,但我们不能分配超对象子类参考什么是你在这种情况下完成的。