This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Object References Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting Object References" Watch "Casting Object References" New topic
Author

Casting Object References

Shiaber Shaam
Ranch Hand

Joined: Jun 16, 2006
Posts: 252
When we type cast object references..... we are casting the references or objects.... Plz clarify......


$Hi/\bEr
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
You are casting the reference type. You can't cast an object.
Shiaber Shaam
Ranch Hand

Joined: Jun 16, 2006
Posts: 252
Ok.. then when do we need to cast references... can u explain some scenarios.... or rules.....
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
One situation where you need to cast references is if a method has a formal parameter which is a supertype of the actual parameter, then when the method is called, that reference will be widened. You have to cast the reference back to the type it was before if you want to call methods on the reference that are defined in the subclass.

Consider this example.



This will produce a compile-time error because no matter what reference type you send to equals, it will be widened to an Object reference.

The class Object does not define the method num().

So you can only call methods on o that are defined in Object.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting Object References
 
Similar Threads
Converting & casting help needed!
Question 58 jiris on casting
Abt Casting...
Casting Throwbale to Exception
Does casting apply to references or to objects? (was Doubt???)