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?

Shape: constructor
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 是正确答案。