Given the code fragment:



public class Person {

    String name;
    int age = 25;

    public Person(String name) {
        this(); // line n1
        setName(name);
    }

    public Person(String name, int age) {
        Person(name); // line n2
        setAge(age);
    }

    //setter and getter methods go here
    
    public String show() {
        return name + " " + age;
    }

    public static void main(String[] args) {
        Person p1 = new Person("Jesse");
        Person p2 = new Person("Walter", 52);
        System.out.println(p1.show());
        System.out.println(p2.show());
    }
}

What is the result?

A.

Jesse 25
Walter 52

B. Compilation fails only at line n1
C. Compilation fails only at line n2
D. Compilation fails at both line n1 and line n2

題解

這題的line n1會發生編譯錯誤,因為Person類別並沒有無參數的建構子。line n2也會編譯錯誤,因為Person(String name)是建構子,沒有辦法直接這樣呼叫,應改成「this(name)」。