Given:
public class SuperTest {
public static void main(String[] args) {
// statement1
// statement2
// statement3
}
}
class Shape {
public Shape() {
System.out.println("Shape: constructor");
}
public void foo() {
System.out.println("Shape: foo");
}
}
class Square extends Shape {
public Square() {
super();
}
public Square(String label) {
System.out.println("Square: constructor");
}
public void foo() {
super.foo();
}
public void foo(String label) {
System.out.println("Square: foo");
}
}
What should statement1, statement2, and statement3, be respectively, in order to produce the result?
Square: foo
Shape: foo
A.
Square square = new Square("bar");
square.foo("bar");
square.foo();
B.
Square square = new Square("bar");
square.foo("bar");
square.foo("bar");
C.
Square square = new Square();
square.foo();
square.foo(bar);
D.
Square square = new Square();
square.foo();
square.foo("bar");
E.
Square square = new Square();
square.foo();
square.foo();
F.
Square square = new Square();
square.foo("bar");
square.foo();
題解
輸出的第 1 行為「Shape: constructor」,因此需要實體化出 Shape 物件才會執行第 13 行的程式。Square 類別繼承 Shape 類別,不傳入參數實體化出 Square 物件也會執行到 Shape 的建構子。如果是傳入字串參數來實體化出 Square 物件的話,雖然也會先執行 Shape 的建構子,但接著還會執行程式第 28 行,多輸出一行「Square: constructor」。所以目前看來,statement1 可以不傳入參數來實體化出 Square 物件,或是實體化出 Shape 物件,且選項 A、B 是錯誤的。
輸出的第 2 行為「Square: foo」,也就是要執行程式第 35 行,Square 類別內的 foo(String label) 物件方法。所以 statement1 應該要實體化出 Square 物件,並且在 statement2 呼叫 Square 物件的 foo 方法時,必須傳入字串參數。因此選項 C、D、E 是錯誤的。
輸出的第 3 行為「Shape: foo」,也就是要執行程式第 17 行,Shape 類別內的 foo() 方法。這個方法在程式第 31 行,也就是 Square 類別內被覆寫,但覆寫的程式實作使用了「super」去呼叫了 Shape 類別原先的 foo() 方法,所以呼叫 Square 物件的 foo() 方法也會輸出「Shape: foo」。選項 F 是正確答案。
