This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes instanceof operator confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof operator confusion" Watch "instanceof operator confusion" New topic
Author

instanceof operator confusion

vernon franks
Greenhorn

Joined: Jul 28, 2013
Posts: 1
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?
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30361
    
150

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

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):


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
 
subject: instanceof operator confusion