2011-11-15 129 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

相關問題