wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 121
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: 121
Hi Guys,

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



Thanks!!

regards
John
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
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.
 
Consider Paul's rocket mass heater.
 
subject: instanceof operator
 
Similar Threads
cast and insatnce operator
Overriding protected method
instanceof operator???
doubt in instanceof
using instanceof in Collection framework