• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceOf - most useless operator ever?

 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1819
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1819
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic