1. 程式人生 > 其它 >抽象類與多型-憤怒的小鳥遊戲

抽象類與多型-憤怒的小鳥遊戲

技術標籤:Java基礎入門多型抽象類java

內容:
定義一個抽象類AngryBirds,具有兩個抽象方法spawn(孵小鳥)和shoot(擊中小豬)。
AngryBirds派生出三個子類:BlueBird、RedBird和WhiteBird。
每個子類都擁有一個私有的成員變數max(孵出小鳥/擊中小豬的最大數量),其中:BlueBird能孵出小鳥/擊中小豬的最大數量為3,RedBird為5,WhiteBird為4。
每個子類實現spawn和shoot方法如下:
public void spawn() {
// 產生一個1~max的隨機數
// 輸出“xBird孵出了x只小鳥”
}
public void shoot() {

// 產生一個0~max的隨機數
// 輸出“xBird擊中了x只小豬”
}
定義一個測試類HitPigGame,在測試類中完成如下功能:
定義一個hitPig方法,利用多型實現AgryBirds的spawn和shoot方法。
定義一個擁有3個數組元素的AgryBirds陣列,3個數組元素分別是BlueBird、RedBird和WhiteBird的物件例項。
呼叫hitPig方法,依次實現三種鳥兒的spawn和shoot方法。
程式執行示例如下:
在這裡插入圖片描述

public abstract class AngryBirds {
    public abstract void spawn();
    public
abstract void shoot(); }
public class BlueBird extends AngryBirds{
    Random rand=new Random();
    private int max=3;        // 孵出小鳥/擊中小豬的最大數量
    public void spawn() {        // 孵出1~max只小鳥
        int x=rand.nextInt(max)+1;
        System.out.println("BlueBird spawn "+x+" children birds."
); } public void shoot() { // 擊中0~max只豬 int x=rand.nextInt(max+1); System.out.println("BlueBird shout "+x+" pigs."); } }
public class RedBird extends AngryBirds{
    Random rand=new Random();
    private int max=5;        // 孵出小鳥/擊中小豬的最大數量
    public void spawn() {    // 孵出1~max只小鳥
        int x=rand.nextInt(max)+1;
        System.out.println("Red spawn "+x+" children birds.");
    }
    public void shoot() {   // 擊中0~max只豬
        int x=rand.nextInt(max+1);
        System.out.println("Red shout "+x+" pigs.");
    }
}
public class WhiteBird extends AngryBirds{
    Random rand=new Random();
    private int max=4;        // 孵出小鳥/擊中小豬的最大數量
    public void spawn() {    // 孵出1~max只小鳥
        int x=rand.nextInt(max)+1;
        System.out.println("WhiteBird spawn "+x+" children birds.");
    }
    public void shoot() {   // 擊中0~max只豬
        int x=rand.nextInt(max+1);
        System.out.println("WhiteBird shout "+x+" pigs.");
    }
}
public class HitPigGame {
    public static void main(String[] args) {
        AngryBirds[] ab=new AngryBirds[3];
        ab[0]=new BlueBird();
        ab[1]=new RedBird();
        ab[2]=new WhiteBird();
        for(int i=0;i<ab.length;i++) {
            hitPig(ab[i]);
        }
    }
    public static void hitPig(AngryBirds ab) {
        ab.spawn();
        ab.shoot();
    }
}