比如现在有个类:
package com.inter;
public class MyClass {
public void output() {
//show something...
}
}
不同的需求下 output() 需要输出不同的信息,要如何在外部将特定的实现代码插入到 output() 中?接下来我们定义一个接口:
package com.inter;
public class MyClass {
private MyInterface mInterface;
public interface MyInterface {
//The abstract method in the interface
public void show();
}
public void output() {
//Call the method of interface
mInterface.show();
}
public void setInterface(MyInterface mInterface) {
this.mInterface = mInterface;
}
}
现在来实现接口:
package com.inter;
public class Main {
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.setInterface(new MyClass.MyInterface() {
@Override
public void show() {
System.out.println("This is my first interface!");
}
});
mc.output();
}
}
这是接口的简单应用。