public class Person { private EatFood eatFood; /** * 普通方式,构造传递引用 */ public Person(EatFood eatSomething){ this.eatFood = eatSomething;//构造时传入引用 } /** * 普通方式,成员函数传递引用 */ public Person(){ } public void setCallBack(EatFood eatSomething) { this.eatFood = eatSomething;//用成员函数传入引用 } //需要调用的方法 public void eatFood() { eatFood.eat(); } }
调用类需要的接口定义
1 2 3
public interface EatFood { void eat(); }
(2)实际调用 一般做法都会写一个类实现接口
1 2 3 4 5 6 7
public class EatRice implements EatFood { @Override public void eat() { // TODO Auto-generated method stub System.out.println("It's time to eat rice."); } }
然后是实际使用的类
1 2 3 4 5 6 7 8 9 10 11 12
public class PeronEatTest { public static void main(String[] args) { //普通方式,构造传递引用 Person personOne = new Person(new EatRice());//EatRice实现类方式。多写一个方法传入也可 personOne.eatFood();
//普通方式,成员函数传递引用 Person personOne = new Person(); EatRice eatRice = new EatRice(); personOne.setCallBack(eatRice); personOne.eatFood(); }
如果使用匿名内部类就便捷了许多
1 2 3 4 5 6 7 8 9 10 11 12
public class PeronEatTest { public static void main(String[] args) { Person personTwo = new Person(new EatFood() { @Override public void eat() { // TODO Auto-generated method stub System.out.println("It's time to eat rice."); } }); personTwo.eatFood(); } }