2012-04-04 2 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

답변

6
d.getMethod(); 

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

에 캐스트 할 수없는 클래스의 개체가 b.getAnotherMethod() 내부적으로를 호출합니다 클래스 C

우리는에 슈퍼 클래스가 참조 서브 클래스 객체를 할당 할 수 있지만, 우리는 슈퍼 클래스이 경우에 당신에 의해 수행되는 서브 클래스가 무엇인지를 참조에 객체 할당 할 수 없습니다.

관련 문제