抽象類最主要的特點相當於制約了子類必須覆寫的方法,同時抽象類中也可以定義普通方法,而且最爲關鍵的是,這些普通方法定義在抽象類時,可以直接調用類中定義的抽象方法,但是具體的抽象方法內容就必須由子類來提供。
定義一個行爲類
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 ;
case EAT + WORK:
this.eat() ;
this.work() ;
break ;
}
}
public abstract void eat() ;//定義子類的操作標準
public abstract void sleep() ;
public abstract void work() ;
}
定義描述人類行爲的子類
class Human extends Action{
public void eat() {
System.out.println("Human supplement energy") ;
}
public void sleep() {
System.out.println("Human begin to sleep") ;
}
public void work() {
System.out.println("Human working hard");
}
}
定義機器人類
class Robot extends Action{
public void eat() {
System.out.println("Robot supplement energy") ;
}
public void sleep() {//此操作不需要但必須覆寫,所以方法體爲空
}
public void work() {
System.out.println("Robot working hard");
}
}
定義豬的類
class Pig extends Action{
public void eat() {
System.out.println("Pig supplement energy") ;
}
public void sleep() {
System.out.println("Pig begin to sleep") ;
}
public void work() {
}
}
測試行爲
class TestDemo {
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);
}
}