理解铸造问题的问题

理解铸造问题的问题

问题描述:

有人可以向我解释评论下的两行是如何编译的吗?理解铸造问题的问题

A a = new A(); 
B b = new B(); 
C C = new C(); 

// How can these work? 
((G) a).methodG(a); 
((B) a).methodG(a); 

public class A { 
    A methodA() { 
     return this; 
    } 
} 
public class B extends A implements G { 
    B methodB(A a) { 
     return this; 
    } 
    public G methodG(A a) { 
     return (G) this; 
    } 
} 

public class C implements G{ 
    C methodC(G g) { 
     return this; 
    } 
    public G methodG(A a) { 
     return (G) this; 
    } 
} 

public interface G { 
    G methodG(A a); 
} 
+3

你是说他们做?因为他们应该在运行时抛出类抛出异常。 – 2011-05-19 19:27:21

+0

他们应该抛出ClassCastException。我检查:) – 2011-05-19 19:28:42

+0

其实我没有看到他们如何工作(在运行时)。 – helpermethod 2011-05-19 19:29:39

他们不会工作。你会得到一个ClassCastException。

编译得很好,因为编译器不知道a不是A的子类,它也实现了G(例如B)。但是,在运行时,当您尝试投射时,它将失败。

这是人们不应该施放的重要原因之一,除非绝对没有选择。它打破了编译器获得的很多类型安全性。

+0

谢谢你快速回答。这是来自我正在参加的课程中的上一年考试。问题的确是要弄清楚哪一行可编译。 – 2011-05-19 19:34:45