Sankaranarayanan Viswanathan wrote:In the below code:
Why does the instanceof operation not result in a compile time error? If Test2 and Test3 were classes instead of interfaces, then the code does result in a compile time error.
If test2 and test3 were class definitions, it is possible for the compiler to determine that there is no way that an instance that IS-A test2 can also be IS-A test3. However, if test2 and test3 are interfaces, it is possible to have an instance that IS-A test2 and IS-A test3, and hence, not possible for the compiler to flag it as a test that can never return true.
The only thing that compiler knows it's that "ob" is implementation of Jkl. And since there can be implementations of Jkl that will also implement Pkl the compilation succeeds.
The compilation succeeds even in the case your declaration is "InterfaceTest ob". That's because InterfaceTest is not declared final, therefore there can be a class that extends it and that implements Pkl. Therefore there's a chance that an object referenced by InterfaceTest (extending it) will implement Pkl and compiler will not complain.