This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
As mentioned in book, "instanceof" operator cannot be used to check different class hierarchies. How does the compiler know that b2 which is a Boat Reference would ever implement Toy(because Boat never implements Toy) or is it that compiler knows the type of object being referred to (which in this would be SpeedBoat) by Boat at compile time?
I modified code just a little so that Boat b2=new Boat(); and then also compiler did not complain. Why? Arent Boat and Toy in different class hierarchies or is that rule an exception because Toy is an interface?
What would be the easiest way to analyze that "instanceof" operator will fail compilation?
You answered yourself instanceof operator checks actual object type at runtime which is in this case SpeedBoat() .As for your second doubt the compiler lets you compare with any interface even if its not in the same hierarchy tree as the object.
Chintan B Shah
Joined: Sep 23, 2008
Thanks for reply.
You answered yourself instanceof operator checks actual object type at runtime which is in this case SpeedBoat() .
Then under what circumstances instanceof will throw compilation error? Is it only when classes are compared and they are not in same heirarchy?