File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes instanceOf - most useless operator ever? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "instanceOf - most useless operator ever?" Watch "instanceOf - most useless operator ever?" New topic
Author

instanceOf - most useless operator ever?

Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

So I thought I had found an errata in a most excellent SCJP book. But when I actually typed in the code, of course the author was correct.



The last line will produce the compiler error:


So the only comparisons that get by the compiler are Object or Component or Ticker.

I thought this would be a run-time thing, and that "no 't' is not a String" would produce boolean false.

So if the only objects that I can use on either side of the operator are *already* in the same tree, I already know that they are in an "IS-A" relation (assuming that the LHS operand is lower in the tree than the RHS).

So what good is instanceOf ?
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1675
Originally posted by Mike Curwen:
So if the only objects that I can use on either side of the operator are *already* in the same tree, I already know that they are in an "IS-A" relation (assuming that the LHS operand is lower in the tree than the RHS).

I don't have any good response to your question in general, but just wanted to point out that what you're saying is not exactly true if the type you're checking against is an interface.
Checking instanceof Iterator below compiles and evaluates to false.
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1675
Ok, I think I'm getting it.
If you upcast your refrence all the way to Object, then the compiler's OK with instanceof String:
Object t7 = new Ticker() ;
boolean test7 = t7 instanceof String ;
System.out.println( test7 );
But if your reference is Ticker (or Component or Marker or SubMarker...), then it knows even at compile time that the check of instanceof is false/not relevant:
Component t8 = new Ticker();
boolean test8 = t8 instanceof String ;
System.out.println( test8 );
=> compiler error
[ February 05, 2003: Message edited by: Michael Matola ]
 
 
subject: instanceOf - most useless operator ever?
 
Threads others viewed
instanceof Problem
Kathy/Bert book ch 3 self test q 2
instanceof question
Question from Ch 3 Self Test, Sierra/Bates Book
instanceof example not compiling
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture