aspose file tools*
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
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: 4387
    
    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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Downcast code question