Given:

class FuelNotAvailException extends Exception {
}

class Vehicle {

    void ride() throws FuelNotAvailException { //line n1
        System.out.println("Happy Journey!");
    }
}

class SolarVehicle extends Vehicle {

    public void ride() throws Exception { //line n2
        super.ride();
    }
}

and the code fragment:

public static void main(String[] args) throws FuelNotAvailException, Exception {
    Vehicle v = new SolarVehicle();
    v.ride();
}

Which modification enables the code fragment to print Happy Journey!?

A. Replace line n1 with public void ride() throws FuelNotAvailException {
B. Replace line n1 with protected void ride() throws Exception {
C. Replace line n2 with void ride() throws Exception {
D. Replace line n2 with private void ride() throws FuelNotAvailException {

題解

FuelNotAvailException 繼承 Exception,屬於 checked exception。

題目原先的程式會在 line n2 編譯失敗,因為 SolarVehicle 的 ride 方法覆寫了 Vehicle 的 ride 方法,Vehicle 的 ride 方法會拋出 FuelNotAvailException,所以 SolarVehicle 的 ride 方法只能不拋出例外、拋出 unchecked exception 或是拋出 FuelNotAvailException 或其子例外。

選項 A,對編譯問題沒有幫助。

選項 B,正確。

選項 C,對編譯問題沒有幫助。

選項 D,可見度需要大於等於 default,使用 private 會編譯錯誤。