• 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

OO doubt (source K&B)

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


I answered B and C, but the correct answers are A and B.
I approached this kind of question with applying instanceof test.

here is my approach...
So, my own answers, for B, dog2 is an object of Beagle(), cast to Beagle, Beagle() is an instanceof Beagle, so CORRECT.
For C, dog2 is of object Beagle(), is an instanceof Beagle, so it is true to be assigned to a Beagle ref.

What is wrong with my approach? please guide!
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Notice that the question asks which lines will compile.

Using the instanceof operator will tell you whether the attempted cast would throw a runtime exception.

Line A will compile because there is an explicit cast telling the compiler that the object is a Beagle. This line will also throw an exception at runtime because the object is not really a Beagle (it would fail the instanceof test). But the question only asks whether it will compile -- not whether it will run.

Line C attempts to assign a reference of type Dog to a variable of type Beagle. This is a downcast (from supertype to subtype), so in order to compile it requires an explicit cast telling the compiler that the object is a Beagle (which in this case, it actually is -- it passes the instanceof test). But without the explicit cast, compilation fails.

Remember, upcasts (from subtype to supertype) are always safe, because it's always true that a an object referenced by a subtype variable IS-A supertype, so no explicit cast is needed. However, it is not always true that a supertype IS-A subtype. Therefore, an explicit cast is required for compilation. And if this cast is wrong, then a runtime exception will be thrown.
[ November 06, 2007: Message edited by: marc weber ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic