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,抽象方法不能有程序实作区块。
