This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "My opinion on Downcasting... and Yours?" Watch "My opinion on Downcasting... and Yours?" New topic
Author

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

Regards
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
Greenhorn

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

flower f=new rose();
r=(rose)f;

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: http://aspose.com/file-tools
 
subject: My opinion on Downcasting... and Yours?
 
Similar Threads
ClassCastException
downcasting
runtime exception
3 Questions
Inner class Vs Outer Class