This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Downcast code question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Downcast code question" Watch "Downcast code question" New topic
Author

Downcast code question

joe bob
Greenhorn

Joined: Feb 13, 2013
Posts: 5
Hi guy,

Why the downcast in this code worked, i know if super class casted down to sub class it generates runtime error, and why it prints 'c' instead prints 'b'?? Thanks guys



Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4377
    
    8

You're actually creating a C object on line 3.

C extends B, so this C is also a B. Therefore when you try and cast the variable to a B, it works. You get an exception when you cast a super-class object to a subclass, but you aren't actually doing that here. The real type of the object is C, which is fine.

Calling the method therefore calls the version in C, as you'd expect - this is polymorphism.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Downcast code question