File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes referrence variable casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "referrence variable casting" Watch "referrence variable casting" New topic

referrence variable casting

anilkumar vankayalapati

Joined: Mar 22, 2006
Posts: 7
what is reference variable casting ,waht can we do with that what is the use of that
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Hi, welcome to the ranch!

Here's an answer that shows a questionable design on an API I use. A base class Entry is extended by File and Folder. I can ask for the entries in a folder that are files or folders or both.

Now I can call all the methods defined by Entry on the objects in this array. But what if I want to deal with Files and call some methods that only exist on File?

The getEntries method tells the compiler it returns Entry objects, so this fails:

Casting tells the compiler something it can't figure out by looking at the code. In the following I'm saying I know this object is really a File even though getEntries does not guarantee it in a way the compiler can understand.

What happens if I mess up and use the FOLDER parameter and then try to cast to File? When I try to cast a Folder to File I'll get an exception.

Finally, note that casting doesn't change the actual object at all. It only gives me a new reference to the object with a different type. With my new reference I can use methods that are defined on the subtype.

Did that help? Can you think of a couple examples you can code up and test? It would be a great experience to cause a cast exception on your own!
[ March 22, 2006: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Consider Paul's rocket mass heater.
subject: referrence variable casting
It's not a secret anymore!