Java Interface as data type
Access Implementations Through Interface References
Once we define an interface
we can use it as a type
for object instance we create through its
implementation class.
Example
The following example calls the callback( ) method via an interface reference variable:
interface MyInterface {
void callback(int param);
}/*from w ww.java 2s. c om*/
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
public class Main {
public static void main(String args[]) {
MyInterface c = new Client();
c.callback(42);
}
}
The output of this program is shown here:
Polymorphism and interface
interface
is designed for polymorphism. interface
defines a list
of methods acting as the contract between the interface and its implementation.
One interface can be implements by more than once and each different implementation
of the same interface would follow the same list of methods. Therefore if we know
several classes implement the same interface we can use that interface to
reference all of its implementer classes.
The compiler will determine dynamically which implementation to use.
interface MyInterface {
void callback(int param);
}/*from w w w . ja v a2 s . c o m*/
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("Client");
System.out.println("p squared is " + (p * 2));
}
}
class AnotherClient implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback");
System.out.println("p squared is " + (p * p));
}
}
class TestIface2 {
public static void main(String args[]) {
MyInterface 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 shown here: