• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Downcasting

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello

How to implement Downcasting in following code


i try this code
child c1=(child) new parent();
for compile time itis ok
but for run time it gives exception
Exception in thread "main" java.lang.ClassCastException: parent cannot be cast to child

thanks in advance
 
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
check the below thread with good discussion on casting. This may help you out-:

Casting
 
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Parent p=new C();
child c1=(child) p;

If you compile your code with these lines your code will run fine at runtime.

In your case new parent() object has the no knowledge of child class that's why at run time it just broke down.
(cast) operator is used for asking compiler to skip checking the compatibilty of the the two operands on either side of = operator, that is why it was fine at compile time.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic