Re: why not compile error on "incompatible interface cast"?
On 7=BF=F927=C0=CF, =BF=C0=C0=FC9=BD=C303=BA=D0, Lew <com.lewscanon@lew> wr=
ote:
gg9h0st wrote:
class IncompInterfaceTest {
void doTest() {
ClassB b = new ClassB();
InterfaceA a = (InterfaceA)b;
}
}
interface InterfaceA{}
class ClassB{}
javac issues "ClassCastException" on runtime rather than compile
error.
as i [sic] know incompatible type casting may be caught at runtime and
compiler shows the error.
Patricia Shanahan wrote:
In general, given a non-final class and an interface, the compiler has
to allow for the possibility that the class has a subclass that
implements the interface.
From the JLS section 5.5:
The detailed rules for compile-time legality of a casting conversion of=
a
value of compile-time reference type S to a compile-time reference type=
T
are as follows:
...
If S is a class type:
...
* If T is an interface type:
o If S is not a final class (=A1=D78.1.1), then, if there exists a su=
pertype X of
T, and a supertype Y of S, such that both X and Y are provably distinct
parameterized types, and that the erasures of X and Y are the same, a
compile-time error occurs. Otherwise, the cast is always legal at compi=
le time
(because even if S does not implement T, a subclass of S might).
Take S as ClassB and T as InterfaceA.
--
Lew
ooooooooowwwww~~ I still don't get it :S
that "a subclass of S might" part.
so compiler doesn't know what variable 'b' hold? that is oviously
ClassB.
if where ClassC extends ClassB implements InterfaceA
b = new ClassC();
means b hold ClassC object in a ClassB variable.
It CAN BE ClassB, It IS NOT ClassB.