Hi,
The JLS abt. the instanceof operator says that.
15.20.2
Type Comparison Operator instanceof
The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (�15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.
Your answer lies in the 2nd Para. The result of the RelationalExpression is true if the reference could be cast to the ReferenceType given that the lvalue(the relationalexpression) is not null.
Now lets analyze ur question
Given classes A,B and C where B is subclass of A and C is a subclass of B, which one of these boolean expressions correctly identifies when an object o has actually been instantiated from class B as opposed to from A or C?
The hierarchy goes like this.
A---->B----->C
As per the language a subclass instance can be implicitly cast to a superclass instance.
Select one right answer.
a.) (o instanceof B) && (!(o instanceof A))
b.) (o instanceof B) && (!(o instanceof C))
c.) !((o instanceof A) | | (o instanceof B))
d.) (o instanceof B)
e.) (o instanceof B) && !((o instanceof A) | | (o instanceof C))
Correct ans given is option b
pls tell me why b is correct and what is the question asking for?
rajashree.
Hence an object o of any class be it A or B or C, will return true for the expression:
o instanceof A coz an object of a subclass gets casted to a superclass implicitly. Hence for the above question to return true the object o should be an instance of Class B and not an instance of any of its subclasses here it means C. Hence option b is the correct answer.
HIH
Arjun