Accessing Implementations Through Interface References

The following example calls the callback( ) method via an interface reference variable:

 
interface MyInterface {
  void callback(int param);
}
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:


callback called with 42

Polymorphic and interface

 
interface MyInterface {
  void callback(int param);
}
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:


Client
p squared is 84
Another version of callback
p squared is 1764
Home 
  Java Book 
    Class  

Interface:
  1. What is a Java Interface
  2. Implementing Interfaces
  3. Accessing Implementations Through Interface References
  4. Partial interface Implementations
  5. Variables in Interfaces
  6. Interfaces Can Be Extended