Given:

package p1;

public interface DoInterface {

    void method1(int n1); // line n1
}
package p3;

import p1.DoInterface;

class DoClass implements DoInterface {

    public DoClass(int p1) {
    }

    public void method1(int p1) {} // line n2

    private void method2(int p1) {} // line n3
}

public class Test {

    public static void main(String[] args) {
        DoClass doi = new DoClass(100); // line n4
        doi.method1(100);
        doi.method2(100);
    }
}

Which change will enable the code to compile?

A. Adding the public modifier to the declaration of method1 at line n1
B. Removing the public modifier from the definition of method1 at line n2
C. Changing the private modifier on the declaration of method 2 public at line n3
D. Changing the line n4 DoClass doi = new DoClass();

題解

題目原先提供的程式會編譯錯誤,因為 DoClass 類別的 method2 方法使用了 private 修飾字來修飾,是私有成員,只有在 DoClass 類別內才可以存取。因此 Test 類別的 main 方法若要存取 DoClass 類別物件的 method2 方法會發生編譯錯誤。

選項 A,介面(interface)定義的方法會自動以 public 修飾字來修飾,因此在 line n1 加上 public 修飾的結果和沒加 public 修飾的結果是一樣的。

選項 B,移除 line n2 的 public 修飾字並不能改變 method2 只能在 DoClass 類別使用的情形。

選項 C,使用 public 來修飾 method2 方法,讓它可以在 DoClass 類別之外被使用,為正確答案。

選項 D,DoClass 類別並沒有無參數的建構子,這樣修改反而會造成更多的編譯問題。