The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Cast with interface

Posted by Chris Goringe on February 12, 2001 at 9:26 PM

Using an interface where you might expect to see a class is not only allowed, but generally good practice - so casting to an interface has to be allowed. As long as the object that is being cast is of a class which implements the interface, there is no problem - every method in the interface MUST be included in the object. If you try to cast an object which is of a class which does not implement the interface, you will get a ClassCastException.

For example, suppose you want to keep a List of Lists (using the interface List from the Java 2 collections framework). When you
pull an object out of a list, all you know is that it is an Object. But you can cast it to a List, and use all the List methods, without knowing or caring what sort of list it is:

Object myObject = masterList.get(0);
List mySublist;
if ( myObject instanceof List )
{
mySublist = (List)myObject;
}
else
{// oh dear. something in the master list wasn't a list.

}


> Hi,
> sometimes I saw code with a cast of an Interface on an object?
> How does it work?
> Example:

> myref = (myInterface) myObject();

> It seems that not all methods from the interface must be included in the object ...??

> I appreciate your help. Thanks

> Dirk






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us