2011-11-15 131 views
1

我学习的SCJP,并在学习期间我发现,起初看起来很简单的运动后,但我失败了解决它,我不明白的答案。演习(从OCP Java SE 6的程序员考试题库,伯特·贝茨和凯西塞拉利昂采取的),说以下内容:调用从主的私人包方法调用构造函数

考虑:

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类中,所以主方法应该可以访问它。

反思的问题,呼吁从静态上下文新时,它可能没有访问私有方法,如果doStuff是私人。这是真的?我不确定这一点。

但无论如何,我仍然认为这将有机会获得包私人doStuff方法。 我想我错了,但我不知道为什么。

你能帮我吗?

谢谢!

回答

4

这是非常可悲的,它不会给你一个答案,为什么将无法​​编译 - 幸好,当你有一个编译器,你可以找到自己:

Test.java:11: error: doStuff(List<String>) in MyPancake cannot implement doStuff 
(List<String>) in Pancake 
    List<String> doStuff(List<String> z) { 
      ^
    attempting to assign weaker access privileges; was public 
2 errors 

基本上接口成员总是公开的,所以你必须用公共方法实现接口。这不是调用方法的问题 - 这是实现接口时遇到的问题。如果你脱下“工具”部分,它会正常工作。

section 9.1.5 of the Java Language Specification

所有接口成员都是public。根据§6.6的规定,如果接口也被声明为公共或受保护,则可以在声明接口的包之外访问它们。

+0

非常感谢!我专注于回顾我的笔记,这本书,但我没有尝试编译它。我应该记住,界面成员总是公开的。 – pablof

2

当你实现煎饼接口。

你在你的类MyPancake

提供的方法doStuff()的实现,当你提供你的MyPancake类中的方法doStuff(),你也应该把它定义为公共的实现,因为所有的成员变量并且接口中的方法默认为public。

因此,当你不提供访问修饰符,它减少了可视性。

+0

也谢谢。我应该已经意识到这个问题在之前是可见的。 – pablof

2

当你定义的方法

List<String> doStuff(List<String> s); 

在煎饼界面,你真正想说的是:

public List<String> doStuff(List<String> s); 

作为一个接口的所有方法始终是公开的,即使你不”明确地将它们标记为这样。

现在,类MyPancake具有分配给doStuff(List s)方法的默认访问权限,因此不会跟随接口并且代码不会编译。

+0

谢谢你的帮助!我忘记了接口中的总是公共成员。 – pablof

相关问题