abstract class Action {// 行为类
public static final int EAT = 1;
public static final int SLEEP = 5;
public static final int WORK = 7;
public void command(int flag) {
switch (flag) {
case EAT:
this.eat();
break;
case SLEEP:
this.sleep();
break;
case WORK:
this.work();
break;
}
}
public abstract void eat();
public abstract void sleep();
public abstract void work();
}
class Robot extends Action {// 机器人类
@Override
public void eat() {
System.out.println("机器人充电补充能量。");
}
@Override
public void sleep() {
}
@Override
public void work() {
System.out.println("机器人不停地工作 ");
}
}
class Human extends Action {
@Override
public void eat() {
System.out.println("渣渣辉正在吃饭!");
}
@Override
public void sleep() {
System.out.println("渣渣辉正在睡觉!");
}
@Override
public void work() {
System.out.println("渣渣辉正在打骨天咯! ");
}
}
class Pig extends Action {
@Override
public void eat() {
System.out.println("猪正在啃菠菜!");
}
@Override
public void sleep() {
System.out.println("猪吃饱了就睡!");
}
@Override
public void work() {
}
}
public class ActionsDemo {
public static void main(String[] args) {
fun(new Robot());
fun(new Human());
fun(new Pig());
}
public static void fun(Action act) {
act.command(Action.EAT);
act.command(Action.SLEEP);
act.command(Action.WORK);
}
}
Java抽象类的定义以及使用(模板设计模式)
最新推荐文章于 2023-10-23 22:05:04 发布