我正在学习SCJP,在学习的过程中发现了一个一开始看起来很简单的练习,但是我没有解决它,我不明白答案。该练习(取自OCP Java SE 6 Programmer Practice Exams、Bert Bates 和 Kathy Sierra)说明如下:
鉴于:
import java.util.*;
public class MyPancake implements Pancake {
public static void main(String[] args) {
List<String> x = new ArrayList<String>();
x.add("3");x.add("7");x.add("5");
List<String> y = new MyPancake().doStuff(x);
y.add("1");
System.out.println(x);
}
List<String> doStuff(List<String> z) {
z.add("9");
return z;
}
}
interface Pancake {
List<String> doStuff(List<String> s);
}
What is the most likely result?
A. [3, 7, 5]
B. [3, 7, 5, 9]
C. [3, 7, 5, 9, 1]
D. Compilation fails.
E. An exception is thrown at runtime
答案是:
D is correct. MyPancake.doStuff() must be marked public. If it is, then C would be
correct.
A, B, C, and E are incorrect based on the above.
我的猜测是 C,因为 doStuff 方法在 MyPancake 类中,所以 main 方法应该可以访问它。
重新考虑这个问题,当从静态上下文调用 new 时,如果 doStuff 是私有的,它可能无法访问私有方法。这是真的?我不确定。
但无论如何,我仍然认为它可以访问包私有的 doStuff 方法。我想我错了,但我不知道为什么。
你可以帮帮我吗?
谢谢!