I believe the other answers are missing one important detail: it is possible because the compiler simply doesn't bother looking into interfaces.
The arguments that are supposed to explain this have been phrased as
there could be class B2 extends B implements I
and
The compiler knows here that A
and B
are not related
These are very true, but it doesn't explain why the compiler knows that these two classes aren't related and not why it can't know if an interface has been implemented.
In the end, these two situations should be rather similar: if it can check at compile time if two classes have a relation, then it should be able to check at compile time if an interface is implemented in that class since both of these situations have their information available at compile time.
Therefore I agree with the comment of Hot Licks in the duplicate:
Because. Even though Cat may not directly implement Furniture, some superclass of Cat may. And the compiler chooses to not dig into such ugly details, since the rules for interfaces are pretty convoluted. (Thank you, Sun.) And there is no general rule requiring the compiler to detect an inevitable runtime exception (such as divide by zero) -- it's more of a "service" it provides.
Checking the interface at compile time should be possible, it's just not done by the compiler for reasons that we can only guess at. that are discussed in the comments.
After an extensive (and very interesting) discussion in the comments below, I believe this has been cleared up.
It is easy and cheap to check if two classes have a relationship, you just look at both their hierarchies. Interfaces on the other hand, require you to have knowledge about all classes and interfaces in the project (including external resources like libraries) in order to determine if there is a relationship between the interface and the class.
This leads me to the conclusion that while it is theoretically possible, it's just not feasible because it would require two things:
- Recompiling your source code and all included libraries.
- Very expensive checks that have to go through the hierarchies of each class.