This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one 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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Downcast code question" Watch "Downcast code question" New topic

Downcast code question

joe bob

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

Joined: Apr 06, 2010
Posts: 4366

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.
It is sorta covered in the JavaRanch Style Guide.
subject: Downcast code question