Using instanceof will result in a compile error if there the two objects being compared are incompatibly different types, as in your Dog and Cat example. Only if there is a chance of the statement being true at runtime will it pass the compiler. So no, you don't have to "typecast" (maybe you meant cast?) objects before using the test, but one class has to be in the hierarchy of the other. (I believe instanceof Interface will always compile.) This make sense sort of, right? Why test for something that can't possibly be true?
(It's been awhile since I've been to this forum. Sorry if I'm breaking a new etiquette rule by answering a question before the user name issue is resolved.)
posted 11 years ago
Greg, Thanks for the clarification. The issue is cleared now. My conclusions are the following -
1) Due to the compile time comprison check, the instanceof keyword returns true by default.
2) Comparison with incompatible types can be done only after typecasting the reference variable to a common class in the inheritance heirarchy.
1. instanceof doesn't return true by "default". I'm not sure what you mean by that.
2. Comparing incompatible types is a waste of time, so the compiler assumes you made a mistake. Referring to a Dog object with an Object reference doesn't involve a cast. (Object o = new Dog(); See? No cast.) However, o might refer to a Cat object later in the code, so the compiler allows the instanceof check to compile.
For my next trick, I'll need the help of a tiny ad ...