You are asked to develop a program for a shopping application, and you are given the following information:



1. The application must contain the classes Toy, EduToy, and consToy. The Toy class is the superclass of the other two classes.
2. The int caicuiatePrice (Toy t) method calculates the price of a toy.
3. The void printToy (Toy t) method prints the details of a toy.

Which definition of the Toy class adds a valid layer of abstraction to the class hierarchy?

A.

public abstract class Toy {

    public abstract int calculatePrice(Toy t);

    public void printToy(Toy t) { /* code goes here */ }
}
B.
public abstract class Toy {

    public int calculatePrice(Toy t);

    public void printToy(Toy t);
}
C.
public abstract class Toy {

    public int calculatePrice(Toy t);

    public final void printToy(Toy t) { /* code goes here */ }
}
D.
public abstract class Toy {

    public abstract int calculatePrice(Toy t) { /* code goes here */ }

    public abstract void printToy(Toy t) { /* code goes here */ }
}

題解

選項A,抽象方法沒有程式實作區塊,非抽象方法有程式實作區塊,因此是正確的。

選項B,非抽象方法必須要有程式實作區塊。

選項C,非抽象方法可以使用final修飾使其不可被覆寫(Override),但其必須要有程式實作區塊。若是抽象方法,則不能使用final修飾,因為需要由繼承的類別來幫抽象方法實作程式區塊。

選項D,抽象方法不能有程式實作區塊。