my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof" Watch "instanceof" New topic
Author

instanceof

Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
From JQPlus
<CODE>
class A {}
class B extends A {}
class C extends B {}
class D extends C {}
public class instanceOF {
static A obj = new B();
public static void main(String args[]) {

boolean b = (obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D);
System.out.print(b);
}
}
</CODE>
Question:
Given the following class definitions, the expression
obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D)
correctly identifies whether the object referred to by obj was created by instantiating class B rather than classes A, C and D?
Ans: False
Explanation:
Correct answer would be(obj instanceof B) && ! (obj instanceof C)
In fact the last part !(obj instanceof D) of the given answer is redundant because anything which is not instance of C cannot be an instanceof D either !
My thought:
Eventhough !(obj instanceof C) is redundant, still the above expression correctly identifies obj to be true if it is a class of B..? So the answer should be True? even though this expression may not be shortest form of evaluation?...

Ragu
[This message has been edited by Ragu Sivaraman (edited December 02, 2001).]
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
it must be false because: "rather than A"
the expression will return true both for A and B instances.


SCJP2. Please Indent your code using UBB Code
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Originally posted by Jose Botella:
it must be false because: "rather than A"
the expression will return true both for A and B instances.

Thankx.
If
static A obj = new A();
boolean b = (obj instanceof A) && ! (obj instanceof C) ;
b would return true too!!
Ragu
 
 
subject: instanceof