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 类别并没有无参数的构造器,这样修改反而会造成更多的编译问题。
