• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof

 
reubin haz
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a question:

Which of the following statements are true?

1) The instanceof operator can be used to determine if a reference is an instance of a class, but not an interface.
2) The instanceof operator can be used to determine if a reference is an instance of a particular primitive wrapper class
3) The instanceof operator will only determine if a reference is an instance of a class immediately above in the hierarchy but no further up the inheritance chain
4) The instanceof operator can be used to determine if one reference is of the same class as another reference thus

I chose 2 and 4, but the correct answer is 2, in the answer, it says 'The instanceof operator can only be used to make a static comparison with a class type', I'm not quite understand what it means.

Can someone explain what 'The instanceof operator can only be used to make a static comparison with a class type' is ?

Thank you.
 
Henry Wong
author
Marshal
Pie
Posts: 20885
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
4) The instanceof operator can be used to determine if one reference is of the same class as another reference


This is false because... well, how would you do it? Say you want to write a method to determine if two objects are the same class. How would you do it? If you don't know if an object is a String, or StringBuffer, or Thread object, you can't determine what class it is. (With only the instanceof operator that is)

Henry
 
Henry Wong
author
Marshal
Pie
Posts: 20885
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The instanceof operator can only be used to make a static comparison with a class type


It is awkwardly worded. I believe the "static" is not the type of the variable, it is referring to the type checking, as is not dynamic.

For example, you can do this:

a instanceof String
a instanceof Thread

But you can't do this:

a instanceof b.getClass()

Henry
[ June 17, 2005: Message edited by: Henry Wong ]
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, why not support this:

if (foo instanceof bar) ...

You could not use the class type on the right since it must work with interfaces. You could assume the declared type of bar. Now you've tied conditional logic to a variable type name that may quietly break in many different ways at runtime. Looks like "object instanceof type" is perfect.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic