2012-04-04 99 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級

我們可以指定子類對象超類引用,但我們不能分配超對象子類參考什麼是你在這種情況下完成的。