• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instanceof operands

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think I finally figured it out! If someone could confirm the following, or correct me, I'd appreciate it.
When using instanceof, if a class is final then a reference of that type must be compared to that class or a superclass or an interface that it or a superclass implements. Won't compile otherwise.
If a class is not final then a reference of that type can be compared to any interface or to a class higher or lower in the inheritance chain.

The reason a non-final class can be compared to a seemingly unrelated interface is that it may be extended by a class that then implements an interface. So you can't be sure, for a non-final class, that an interface won't be implemented further down the inheritance chain.
I can't tell you how long I've been struggling with this. And of course I'm to stubborn to ask without trying to figure it out first.
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Derek, your description is consistent with the JLS, and your reason is correct.
I see that you are working on (and having trouble with) this case:
x instanceof K
where x is of class type and K is an interface type
----
I analyze instanceof in terms of the allowed widening and narrowing conversions:
A conversion from a class type S to an interface type K is a widening conversion, provided S implements K.
A conversion from a class type S to an interface type K is a narrowing conversion, provided S is not final and does not implement K. (A subclass of S might implement K.)
The missing case, the one that is neither a widening nor a narrowing conversion is, S is final and S does not implement K.
----
At compile time, x instanceof K accepts both widening and narrowing conversions. A narrowing conversion must be checked at run-time, using the type of the object.
The widening and narrowing conversions are listed in JLS 5.1.4 and 5.1.5.
[ December 10, 2003: Message edited by: Marlene Miller ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic