This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line! See this thread for details.
Hum, I think you are not right Mike. You have to consider the hierarchy of the classes of the object being compared. Variable o is declared as Object, but it holds a reference to a ICheck instance. ICheck extends Check, which extends Object, just like any other java class. Therefore it is a instance of any of these classes, and will passa the instanceof comparation for any of these. If you compare any object with the class Object (xxx instanceof Object), the comparation will be true, because every object extends Object. But remember, the object in the left MUST BE of the same class or a subclass of the class on the right. Hope I've made myself clear. s Pedro Ivo
I tested the three possibilities, o instanceof Object o instanceof ICheck o instanceof Check
they all compile OK.
The question didn't ask if the conditional was true, it asked if it was legal, meaning it compiles and excutes without error. In this case, the three possibilities are also true, since o is an instance of class ICheck and ICheck is a subclass of both Check and Object.
Weel, just to make this topic clear: when using the instanceof operator, the left operand can be any java object, while the right hand can be any java class. It will return true if the object is a instance of the class, or any of it subclasses. This relation is also valid for interfaces.
I know I sound like a language lawyer, but the left side of instanceof is an object reference, not an object. To avoid a compilation error, there must be some class whose instances could both be referenced by the left operand and be cast to the right operand class.
In other words, "a instanceof B" is legal if there is some possible code that would make that expression true. If that is impossible, Java warns you at the compilation stage.
Consider this code:
In "b instanceof A", I could assign a B object to b to make the expression true.
In "a instanceof B", I could assign a B object to a to make the expression true.
In "b instanceof C", there is nothing I could legally assign to b to make the expression true, so the Java compiler warns me that it thinks I made an error. [ November 19, 2004: Message edited by: Mike Gershman ]