• 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 operator confusion

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy yallll javacoffeecuppajoe here.....

I am learning intermediate Java and I am having confusion over one aspect of the instanceof operator. I know what it is used for and how to use it. What I am confused about though is why the operator cannot test for siblings in a class tree. Suppose I have a Class A, and Class B extends Class A. Then I make another class, Class C extends class A. Class B and Class C are siblings of Class A. It seems you cannot test instances of one sibling against the type of the other sibling. For instance:



The compiler complains of "Incompatible conditional operand types B and C" or something like that.


Why?
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

Because there is no chance of it being true at runtime. Instanceof will only compile if it might be true. If it can never be true, it is unreachable code. The compiler recognizes this and tells you. The solution being to fix the if condition to something possible or get rid of it.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that it will work if you change the type of the variable instance_B to for example Object (or any other superclass of C to which you can also assign a B):
 
reply
    Bookmark Topic Watch Topic
  • New Topic