Why in this snippet while Tree interface is not related to Bug class it does not produce compile time exception?
interface Tree {}
class Bug {
public static void main(String[] args) {
Bug bug = new Bug();
Tree tree = (Tree) bug;
}
}
Mark Bug
as final
and you will get your compiler error as expected.
This is because Bug
could have a subclass that does implement Tree
. If bug
actually stores a reference to an instance of that subclass, then the cast will succeed. Since there is a chance that the cast can succeed, the compiler doesn't stop you from casting.
In most cases, you can cast from any non-final class to any interface. According to the JLS §5.5.1 , when you try to cast a variable of reference type S
to interface T
:
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 ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.