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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.