阿摩線上測驗 登入

申論題資訊

試卷:101年 - 101年高等三級暨普通考普通_資訊處理#29393
科目:程式設計
年份:101年
排序:0

申論題內容

三、一個簡化的龜兔賽跑系統有以下 3 個類別,請以 Java 語言撰寫這 3 個類別的完整定 義:(30 分) Animal 類別代表動物,是一個抽象類別(abstract class),它有 1 個 private 屬性 name 與 1 個 protected 屬性 speed,分別代表動物名稱與速度;有 1 個 public static 常數 DISTANCE,其值為 1000,代表賽跑的總距離;它有一個無引數建構子(noargument constructor),會將 name 設定為“No Name”,將 speed 設定為 1;也有一 個二引數建構子(two-argument constructor),會將 name 與 speed 分別設定為傳入 之參數 theName 與 theSpeed;它也有 1 個 toString()方法會傳回動物名稱與速度合併 後的字串;它有 1 個 time()的抽象方法(abstract method),用以計算動物跑完全程 所需時間。 Turtle 類別代表烏龜,是 Animal 的衍生類別。它的無引數建構子會呼叫 Animal 的 無引數建構子;它的二引數建構子會呼叫 Animal 的二引數建構子;它的 time()方法 會傳回烏龜跑完全程所需時間。它的 toString()方法會先呼叫父類別的 toString()以取 得名稱與速度,並與 time()所計算的時間,合併成一個字串後傳回。 Rabbit 類別代表兔子,是 Animal 的衍生類別。它有一個 private 的屬性 sleep,代表 兔子在比賽開始後睡覺的時間。它有一個無引數建構子,會先呼叫 Animal 的無引 數建構子,然後將 sleep 設定為 0;它有一個三引數建構子,會先呼叫 Animal 的二 引數建構子,然後將 sleep 設定為傳入之第 3 個參數 theSleep;它的 time()方法會傳 回兔子跑完全程所需時間,此時間需包含兔子睡覺的時間。toString()方法會先呼叫 父類別的 toString()以取得名稱與速度,並與 sleep 時間,以及 time()所計算的時間, 合併成一個字串後傳回

詳解 (共 1 筆)

詳解 提供者:hchungw
Animal 類別(抽象類別)
java
Copy code
public abstract class Animal {
    private String name;
    protected int speed;
    public static final int DISTANCE = 1000;
    // 無參數建構子
    public Animal() {
        this.name = "No Name";
        this.speed = 1;
    }
    // 有參數建構子
    public Animal(String theName, int theSpeed) {
        this.name = theName;
        this.speed = theSpeed;
    }
    // toString 方法
    @Override
    public String toString() {
        return name + " with speed " + speed;
    }
    // 抽象方法
    public abstract double time();
}
Turtle 類別(烏龜)
java
Copy code
public class Turtle extends Animal {
    // 無參數建構子
    public Turtle() {
        super();
    }
    // 有參數建構子
    public Turtle(String theName, int theSpeed) {
        super(theName, theSpeed);
    }
    // 覆寫 time 方法
    @Override
    public double time() {
        return (double) DISTANCE / speed;
    }
    // 覆寫 toString 方法
    @Override
    public String toString() {
        return super.toString() + ", Time: " + time() + " hours";
    }
}
Rabbit 類別(兔子)
java
Copy code
public class Rabbit extends Animal {
    private int sleep; // 兔子睡眠時間
    // 無參數建構子
    public Rabbit() {
        super();
        this.sleep = 0;
    }
    // 有參數建構子
    public Rabbit(String theName, int theSpeed, int theSleep) {
        super(theName, theSpeed);
        this.sleep = theSleep;
    }
    // 覆寫 time 方法
    @Override
    public double time() {
        return ((double) DISTANCE / speed) + sleep;
    }
    // 覆寫 toString 方法
    @Override
    public String toString() {
        return super.toString() + ", Sleep: " + sleep + " hours, Total Time: " + time() + " hours";
    }
}
這些類別滿足題目的所有要求,包括抽象類別Animal定義的特性和方法,以及Turtle和Rabbit類別的具體實現。這裡假設動物賽跑的時間單位為小時。