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 My opinion on Downcasting... and Yours? 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 "My opinion on Downcasting... and Yours?" Watch "My opinion on Downcasting... and Yours?" New topic

My opinion on Downcasting... and Yours?

Ramakrishna Nalla
Ranch Hand

Joined: Apr 21, 2005
Posts: 61
hi.. I am posting my opinion on downcasting concept...
pls follow this code first..

My opinion

Downcasting ony possible at runtime(as I know)

Steps to Dwonccast::

1)Subclass reference varibale must be initialized
Ex: rose r=new rose();
2)The superclass reference varible MUST CAST TO (either explicitly or implicitly) SUBCLASS OBJECT...
Ex: f=r; where f is superclass reference variable... r is subclass reference variable
If not ...runtime error 'ClassCastException' occurs
3)Now we can downcast explicitly..

Is my conclusion correct or not....pls post your comments on downcasting.
Tahnk You

Ramakrishna Nalla
[ June 19, 2005: Message edited by: Ramakrishna Nalla ]
narendra darlanka
Ranch Hand

Joined: Jun 17, 2005
Posts: 66
that can be simply said as ,downcasting an superclass reference variable to an subclass reference variable is possible only if the super class variable actually refers to an instance of subclass or an subclass of the subclass....down the hierarchy

~naren<br /> scjp1.4<br /> scwcd1.4
Sangita Mishra

Joined: Jun 15, 2005
Posts: 22
Yes, narendra is right. You can also do this:

flower f=new rose();

You don't need f=r here as f is a reference to a rose object.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Safety First

void foo(Object object)
assert object instanceof Moose;
Moose moose = (Moose)object;
I agree. Here's the link:
subject: My opinion on Downcasting... and Yours?
It's not a secret anymore!