File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof Operator Question - K&B Book-Chapter 4 self-test section Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof Operator Question - K&B Book-Chapter 4 self-test section" Watch "instanceof Operator Question - K&B Book-Chapter 4 self-test section" New topic
Author

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

Chintan B Shah
Ranch Hand

Joined: Sep 23, 2008
Posts: 83
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.


SCJA 1.0
S Ali
Ranch Hand

Joined: Aug 23, 2009
Posts: 129
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.


SCJP 6
Chintan B Shah
Ranch Hand

Joined: Sep 23, 2008
Posts: 83
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

Joined: Sep 06, 2009
Posts: 531
yes...
Chintan B Shah
Ranch Hand

Joined: Sep 23, 2008
Posts: 83
Thnx Ali and Ankur.

Regards,
Chintan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof Operator Question - K&B Book-Chapter 4 self-test section