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
Java Book
Class
Interface:
- What is a Java Interface
- Implementing Interfaces
- Accessing Implementations Through Interface References
- Partial interface Implementations
- Variables in Interfaces
- Interfaces Can Be Extended