Get your CodeRanch badge!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Downcasting 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 "Downcasting" Watch "Downcasting" New topic
Author

Downcasting

ABHIJEET BUDKE
Greenhorn

Joined: Sep 20, 2007
Posts: 8
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
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Hi,
check the below thread with good discussion on casting. This may help you out-:

Casting
gurneeraj singh
Ranch Hand

Joined: Mar 19, 2008
Posts: 80
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.


SCJP 5.0 93%<br /> <br />SCWCD 5.0 97 %
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Downcasting
 
Similar Threads
question about polymorphism
Question (...Inheritance)
clarification on why the modifier private changes output..
Problem -- Virtual Method Invocation
About Overridden II (a Mock Question question...)