This week's giveaway is in the Java/Jakarta EE forum.
We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!

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 ]
It is difficult to free fools from the chains they revere - Voltaire. tiny ad:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!