Using an interface as a type
I've been looking through some production code, and I'm a little confused on the concept of using an interface as a type (object)
I saw this explanation http://download.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
Here's the code below:
public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable开发者_C百科 obj2 = (Relatable)object2;
if ( (obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}
Where Relatable
is an interface, I don't understand where it gets the logic for the isLargerThan(obj2)
function call.
Can somebody make this clear for me?
The logic comes from the class which implements the interface. This is exactly the reason why you cannot directly instantiate an interface, because the interface itself doesn't contain any implementation. The language ensures that the objects passed to your method are of a concrete class that implements the methods in the interface.
While the compile time type of obj1
is Relatable
, the runtime type is some concrete class that implements Relatable
. The code that actually gets called is defined by that runtime type. This is known as dynamic dispatch.
It's assumed that the objects are actually of types that implement the interface; otherwise, you'd get a ClassCastException
when casting.
精彩评论