• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof

 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it must be false because: "rather than A"
the expression will return true both for A and B instances.
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic