你应该使用
interface来做。
您将传递所需功能的界面传递给该方法,并调用所需的方法。将被调用的具体方法是由实现类实现的方法。
代码示例:
public static interface Foo { //this is the interface declaration
public void print();
}
public static class Bar implements Foo { //Bar is an implementing class
public void print() {
System.out.println("Bar");
}
}
public static void test(Foo foo) { //the method accepts an interface
foo.print(); //and invokes it, the implementing class' print() will be invoked.
}
public static void main(String... args) throws Exception {
test(new Bar()); //invoke test() with the class implementing the interface
}