This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof operator" Watch "instanceof operator" New topic
Author

instanceof operator

John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 132
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

Joined: Apr 09, 2011
Posts: 158
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

Joined: Feb 28, 2007
Posts: 79
you are using it like "obj1 instanceof obj2"
actually it is meant to be used like "obj1 instanceof Class" or "obj2 instanceof Interface"


lavnish.blogspot.com
John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 132
Hi Guys,

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



Thanks!!

regards
John
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: instanceof operator