aspose file tools*
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

akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
how downcasting is done.when we need downcasting??


We will keep things moving!!
Paul Stat
Ranch Hand

Joined: Jan 20, 2009
Posts: 50
For primitives it's something along the lines of



You have to do the cast as there's a possible loss of precision (going from a larger to smaller primitive type)

If however your going from a smaller to larger primitive type then the casting is implicit

akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
in case of inheritence how downcasting is done
Paul Stat
Ranch Hand

Joined: Jan 20, 2009
Posts: 50
Like so

akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
can you please tell me the basics of casting this example is not clear .how casting is performed here.can you please explain
chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Posts: 629

do you have Kathy Sierra book for SCJP ?


http://www.androcid.com/
Paul Stat
Ranch Hand

Joined: Jan 20, 2009
Posts: 50
akash azal wrote:can you please tell me the basics of casting this example is not clear .how casting is performed here.can you please explain


What "basics" do you want to know, your question is somewhat vague. You've asked how to cast with inheritance I've shown you, do you want something more specific?
akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
// ClassCasts cc2 = mc1; //does not compile

why this will not compile??

yha i am having k&S book
Paul Stat
Ranch Hand

Joined: Jan 20, 2009
Posts: 50
akash azal wrote:// ClassCasts cc2 = mc1; //does not compile

why this will not compile??

yha i am having k&S book


Because you're changing the ClassCast object reference cc2 to reference a MasterClass instead, which could lead to "Possible loss of precision". Basically the compiler is saying "Are you really sure you want to do that?"
ram prabu
Greenhorn

Joined: Dec 23, 2008
Posts: 15
hi

There is two types of reference casting
1. upcasting( implicit casting)
you just assing your subclass object referece to superclass
Ex: subclass sub=new subclass();
superclass sup=sub;
Because subclass know about the superclass by extending of superclass.

2. downcasting ( Explicit casting)
That means your superclass object referece is assing to subclass
EX: superclass sup=new superclass();
subclass sub=(subclass) sup;
here your superclass don't know about subclass, so it throws a classcastexception at runtime
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: downcasting