I have read that instanceof operator can not be used on the instances/classes that belong to different inheritance tree and that it will result in compile error. But now I have come across this example:
And as I look in the book HashMap and Collection are in completly different inheritance tree but the above code still works. Can anyone explain why?
Collection is an interface, not a class.
Interfaces are different from classes - they are not in the class inheritance tree, there are 'oudside' of this tree.
Where an interface is on the right side of instanceof operator, the operator tests if given object implements that interface.
Virtually all classes can implement any interface, and compiler cannot reject this test at compile time.
Look at this example:
Here we have:
1. interface Collectionnn
2. two clasess: HashMappp, HashMappp_Collection in one 'inheritance subtree'
3. third class: OtherClass that is in the other 'inheritance subtree' than classes from point 2.
HashMappp doesn't implement Collectionnn, but two other classes do.
posted 10 years ago
Thanks you for the answer and a great example! Yeah, that's straightforward now. A class can implement any interface so instanceof operator can not reject it !