aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting to an Interface Type 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 "Casting to an Interface Type" Watch "Casting to an Interface Type" New topic
Author

Casting to an Interface Type

Christian Garcia
Ranch Hand

Joined: Jan 29, 2002
Posts: 77
I've read that you can cast an instance of a class that implements an interface to a reference variable of the interface type:

The question I have is why would you want to do this and what are the benefits?
CG


Christian
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Christian
There are a couple of reasons you might want to do that, both closely related.
First off the purpose of having interfaces (other than as a way of implementing multiple inheritance) is to specify common behavior between all of its implementing classes. A classic example of this is by using them to create callbacks. C and C++ programmers know of these by passing pointers to functions back and forth and around - pretty confusing actually (at least to me). In Java it is easier - we use interfaces. Look at Runnable and then look at the constructor for a Thread. Thread takes a Runnable object (anything that implements Runnable) and 'registers' that objects run method as the target of the threads start method.
In most cases you dont need to actaully cast up to the interface type - its an upcast and should happen implicitly. Downcasting to the original type is more common.
hope that helps mopre than it confuses


Dave
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
just a small thing:
u dont actually have to do the casting here.
upcasting is done automatically so this is enough:
SampleInterface x = pet;
without the (SampleInterface)...
mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
object of the class that implements this interface
is implicitly an object of the interface itself.
SampleInterface x = pet;
is how one would get an object for the interface. i have never seen the casting done like below
SampleInterface x = (SampleInterface)pet
i don't think this sounds correct ? does it ? curious to know because i have never seen such a cast.
Originally posted by Roy Ben Ami:
just a small thing:
u dont actually have to do the casting here.
upcasting is done automatically so this is enough:
SampleInterface x = pet;
without the (SampleInterface)...
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5019
    
    8

Christian,
You may cast an object reference to assign it to an interface reference but you really don't have to. The compiler knows whether or not a class implements a particular interface so it really doesn't need the cast to help it determine whether the assignment is legal.
The cast is only needed if you try to assign an interface reference to an object reference. Since it is possible that the actual object referenced by the interface type variable is not compatible with the class type reference, the compiler requires the extra assurance of the cast. The cast is like you telling the compiler "I give you my word that the actual object being referenced by the interface variable is compatible with the object reference".
The benefits of using interface types instead of class types is flexibility in both the client and the provider/implementer code.
Think of the interface as a "Level of Service" contract: it defines a set of services that implementers must guarantee to provide to clients.
If you use interface type references in your client code exclusively, you can easily switch to a different provider without fear of breaking any code. On the other hand, if you use class type references in client code, you are locking yourself into one particular implementation. If your code relies too much on a particular implementation, then switching implementations will be tedious at best.
On the other side of the interface, the implementer (the one providing the services defined by the contract) is free to do whatever it needs to do to provide the services. If at some later time you find a better and cheaper way to provide the same services, then you can make those improvements without fear of breaking any client code.

[ February 04, 2002: Message edited by: Junilu Lacar ]

Junilu - [How to Ask Questions] [How to Answer Questions]
Rick Reumann
Ranch Hand

Joined: Apr 03, 2001
Posts: 281
One of the most powerful uses of being able to use interfaces is to demonstrate polymorphism. Notice in the code below each Animal in the array loop is really of a particular type (either Dog or Cat )
Christian Garcia
Ranch Hand

Joined: Jan 29, 2002
Posts: 77
Thank you to all that commented on my question.
I realize that my sample code wasn't the best example and actually didn't require the cast that I was trying to figure out. After reading the replies I understand the reasons/benefits for using interface types. There are a few things I need to work on to solidify this, but at least now I know where to start
Thanks!!
CG
Christian Garcia
Ranch Hand

Joined: Jan 29, 2002
Posts: 77
Junilu,
Is the technique of using interface references in place of object references a common practice or is it reserved for Enterprise level development?
I find it intruiging and would like to know more about it.
CG
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5019
    
    8

Christian,
Joshua Bloch, author of "Effective Java Programming Language Guide" and the Collection API, advises that you should
"...favor the use of interfaces rather than classes to refer to objects. If appropriate interface types exist, parameters, return values, variables, and fields should all be declared using interface types. The only time you really need to refer to an object's class is when you're creating it...If you get into the habit of using interfaces as types, your program will be much more flexible."

[ February 05, 2002: Message edited by: Junilu Lacar ]
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Hello Christian,
just to complete about interface casting

class Base {}
class Derived extends Base implements Cloneable {}
Derived derived = new Derived();
Cloneable clon = derived;

It is not necessary an explicit cast because the assignment is towards a supertype. The interfaces that a class implements are supertypes of it.
An explicit cast is not needed wherever the LHS and RHS of the assignment are of equal type, or the RHS is being assigned towards one of its supertypes.
At runtime any method possibly defined in the interface, could be called on the clon variable. Because it holds an instance that implements it. Thus no ClassCastException is thrown at run time because of this cast.
However

class Base {}
class Derived extends Base {}
Base base = new Derived();
Cloneable clon = (Cloneable) base;

An explicit cast is needed. The compiler is allowing to cast a reference of type Base to an interface that it doesn't implement. Why? because one of its subclasses could implement it. For this to work at compile time the class must not be final. Or, if it is final it must implement the interface to be casted on.
Because the Derived class doesn't implement the interface, at runtime a ClassCastException is thrown. This is so to prevent a clon variable from holding an instance of a type that is not really of that type. If this cast were allowed at runtime, the instance hold by clon could not respond to messages defined in an interface that doesn't implement.
So we are assurred that a variable holds an object that can respond to the methods declared in the type of the variable or its supertypes.
Read more about casting on JLS 5.5


SCJP2. Please Indent your code using UBB Code
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9052
    
  12
Christian,
'G' is not an acceptable lastName that conforms to the naming policy required here at JavaRanch. Please edit your profile to conform.

Thanks.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
 
subject: Casting to an Interface Type