• 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

OCPJP 6: Downcasting

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

In the Whizzlabs tests for objective 5, there is the following question:
https://dl.dropboxusercontent.com/u/38167918/Computing/OCPJP/WhizLabs/Objective5/DownCasting1.JPG

The correct answer is that a ClassCastException is thrown at runtime. It is mentioned that line 3 causes this to happen. However line 3 looks like a downcast to me, so I don't understand why it would cause that exception.
It is also mentioned that line 4 would not give a problem because the interface type is being cast to the Base type, which also seems like a downcast to me, and this is fine and not causing any exception!! Hope someone can explain. Thank you.

regards
John.
 
Bartender
Posts: 3648
16
Android Mac OS X Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The question in concern is:


Line 1 b is a Base which upcast to i => valid because Base is a Inter
Line 2 d is a Derived which upcast to Base then assign to Inter => valid because Derived is a Base and Base is a Inter]
Line 3 b is a Base which downcast to Derived => not valid ClassCastException, forget assigning to bd (a Derived)
Line 4 i is NOT a Inter from line 1 but the i from line 2 hence it's really a Base so casting it to a Base is valid and assigning to b (a Base) is also valid

Hope this helps.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic