Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

My opinion on Downcasting... and Yours?

 
Ramakrishna Nalla
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sangita Mishra
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Safety First

void foo(Object object)
{
assert object instanceof Moose;
Moose moose = (Moose)object;
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic