Reputation: 979
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);
}
Upvotes: 2
Views: 96
Reputation: 40811
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.
Upvotes: 4