Why can we use the Java interface for * any * non-final class?

import java.util.Collection; public class Test { public static void main(String[] args) { Collection c = null; Test s = null; s = (Test) c; } } 

In the above code example, I throw the collection object into the Test object. (ignoring the null pointer). The test is not related to the collection at all, but this program will pass all the compile-time checks.

I wonder why this is so. My guess is that interfaces are ignored because they are too complex. They don’t have a common supertype, and each class can implement several interfaces, so the class / interface hierarchy will be too complicated for an efficient search?

Besides, I'm still dumb. Somebody knows?!

+4
source share
2 answers

"Nefinal" is the key word here. You may have a different class

 public class Test2 extends Test implements Collection 

whose instance will eventually be assigned to s , making the cast completely legal.

+8
source

Since the subclass Test could potentially be a subtype of Collection ! The language specification is designed to be a little flexible to allow checks that can be checked at runtime.

+3
source

All Articles