File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 4542

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.
I agree. Here's the link:
subject: Downcast code question
It's not a secret anymore!