无法理解选角问题
有人可以向我解释一下注释下的两行是如何编译的吗?
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);
}
Can someone explain to me how the two lines under the comment are compilable?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们不会工作。您将得到一个 ClassCastException。
它会编译得很好,因为编译器不知道a不是也实现G的A的子类(例如B)。但是,在运行时,当您尝试强制转换时,它将失败。
这就是人们不应该选角的重要原因之一,除非别无选择。它破坏了编译器获得的很多类型安全性。
They won't work. You'll get a ClassCastException.
It will compile fine, since the compiler doesn't know for a fact that a is not a subclass of A that also implements G (for example B). However, during runtime, when you try to cast, it will fail.
And this is specifically one of the big reasons people shouldn't cast unless there's absolutely no choice. It breaks a lot of the type-safety you get with the compiler.