Meaningless Drivel is fun!
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof operator" Watch "instanceof operator" New topic

instanceof operator

John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 170
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 file compiles fine but when I compile the 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.

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"
John Paterson
Ranch Hand

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

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


Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46323
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.
I agree. Here's the link:
subject: instanceof operator
It's not a secret anymore!