Accessing Implementations through Interface References
You could define variables as object references which use an interface rather than a class type. Any object of any class which implements the declared interface can be stored in like a variable. Whenever you call a function by one of these references, a right version will be called based on the original instance of the interface being referred to. This is one of the key concepts of interface. The function to be executed is looked up dynamically at runtime, permitting classes to be created later than the code that calls methods on them. A calling code can dispatch by an interface without having to know anything about the "callee".
The subsequent instances calls the callback ( ) method through an interface reference variable:
class TestIface {
public static void main (String args [ ]) {
Callback c = new Client ( ) ;
c.callback (42);
}
}
The output of this program is:
callback called with 42
Remember that variable c is defined to be of the interface type callback; still it was assigned an instance of client. While c can be used to access the callback ( ) functions, it cannot access any client class other members. An interface reference variable only has knowledge of the methods declared through its interface declaration. Therefore, c could not be used to access nonIfaceMeth ( ) because it is defined through client but no Callback.
Although the preceding instance mechanically, displays, how an interface reference variable can access an implementation object, it does not elaborate the polymorphic power of such a reference. For sample this usage, firstly create the second implementation of Callback that are display here:
/ / Another implementation of Callback
class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println ("Another version of callback");
System.out.println ("p squared is "+(p*p));
}
}
Further, try the subsequent class:
class TestIface2 (
public static void main(String args []) {
Callback c= new Client ( ) ;
AnotherClient ob = new anotherClient ( );
c.callback (42);
c = ob; / / c now refers to AnotherClient object
c.callback (42) ;
}
}
The output from this program is:
Callback called with 42
Another version of callback
p squared is 1764
As previously you can see the versions of callback ( ) which is called is determined through the type of object which c refers to at run time. Although this is a extremely simple example, you will see another, more practical one shortly.