Java Interface as data type

In this chapter you will learn:

  1. How to access implementations through interface references
  2. Example - Java Interface as data type
  3. How to use interface to do polymorphism

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  w  w. ja va2 s.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 ww  .j  a v  a  2s . 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:

Next chapter...

What you will learn in the next chapter:

  1. How to partially implement an interface
  2. How to use interface to organize constants
  3. How to extend interface