• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof Operator Question - K&B Book-Chapter 4 self-test section

 
Chintan B Shah
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,



My dilemma is this line b2 instanceof Toy.

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?

Thanks
Chintan.
 
S Ali
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ali,

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?

Regards,
Chintan.
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes...
 
Chintan B Shah
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx Ali and Ankur.

Regards,
Chintan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic