用顾客点餐可以做一个例子:
这是接口(菜单):
package test01;
//接口menu
interface menu {
void FriedRice();
void ChickenNugget();
}
这是西方厨师做菜:
package test01;
//WstCooker 实现menu接口
public class WstCooker implements menu{
public void FriedRice() {
System.out.println("Western cooker can cook Fried Rice!");
}
public void ChickenNugget() {
System.out.println("Western cooker can cook Chicken Nugget!");
}
}
这是东方厨师做菜:
package test01;
//EstCooker 实现menu接口
public class EstCooker implements menu{
public void FriedRice() {
System.out.println("Eastern cooker can cook Fried Rice!");
}
public void ChickenNugget() {
System.out.println("Eastern cooker can cook Chicken Nugget!");
}
}
这是顾客类:
package test01;
public class customer {
//封装
private menu m;
//Setter 用menu m 传参 当在主函数测试的时候可以实现多态
public void setMenu(menu m) {
this.m = m;
}
//Getter return menu 类型
public menu getMenu() {
return m;
}
}
测试主函数:
package test01;
public class test01 {
public static void main(String[] args) {
//创建customer对象
customer c = new customer();
//创建东方厨师对象
EstCooker ec = new EstCooker();
c.setMenu(ec);
c.getMenu().FriedRice();
c.getMenu().ChickenNugget();
//创建西方厨师对象
WstCooker wc = new WstCooker();
c.setMenu(wc);
c.getMenu().FriedRice();
c.getMenu().ChickenNugget();
}
}
输出结果:
?
|