Originally posted by Cathy Song:
Given three classes A, B, and C, where B is subclass of A and C is subclass of B, which one of these boolean expressions is true when an object denoted by reference o has actually been instantiated from class B as opposed to from A or C?
choices:
1. (o instanceof B)
2. (o instanceof B) && (!(o instanceof C))
I think both these answers are right, but the ans given is 2.
Why?
--Cathy.
I agree with you Cathy.
You can also look at it this way without thinking about the classes.
&& is a short-circuit operator. So for (2) to be true, then the 1st expression must be true, otherwise, it will immediately return false and ignore the 2nd expression. Now the 1st expression in (2) is (o instanceof B). And if this is true, then (1) must also be true.
[ October 14, 2003: Message edited by: Alton Hernandez ]