Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator

 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

I was playing around with the instanceof operator to better understand it when I ran into the some trouble. Follwing are the 2 source files in question:


The 'Car' class


The 'Merc' class


The Car.java file compiles fine but when I compile the Merc.java file, I am getting the following error:

symbol : class car
location: class polytest.Merc
if (mrc instanceof car) {
1 error


I am not sure why I am getting this. Both classes are in the same package, Merc extends Car and I have also created an instance of Car in the Merc class. I hope someone can advise me on this. Thanks.

regards
John
 
Walter Gabrielsen Iii
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The car (lower-case) is an object reference and Car (upper-case) is a class, instanceof wants a class.

Or, to be most specific: ([variable] instanceof [class]).

Another option is: (car.getClass().isInstance(mrc)).
 
lavnish lalchandani
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are using it like "obj1 instanceof obj2"
actually it is meant to be used like "obj1 instanceof Class" or "obj2 instanceof Interface"
 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

Thanks for the replies. I tried this and it works:



Thanks!!

regards
John
 
Campbell Ritchie
Sheriff
Pie
Posts: 49457
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beware of instanceof. When you find yourself querying the type of an object, you should wonder whether you have made a design mistake. In this case you are obviously using it to find out how the operator works, which is always all right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic