Java中protected方法訪問權限的問題


先看Test.java

 

此時出現上文提到的錯誤:The method clone from the type Object is not visiuable.

我們已經清楚Object.clone()是protected方法。這說明,該方法可以被同包(java.lang)下以及它(java.lang.Object)的子類訪問。這里我們自己定義的MyObject類(默認繼承java.lang.Object)。

同樣Test也是java.lang.Object的子類。但是,不能在一個子類(Test)中訪問另一個子類(MyObject)的protected方法,盡管這兩個子類繼承自同一個父類(Object)。其實這是由於調用MyTest的Clone方法實際上是調用MyTest的父類Object的Clone方法。第一,Object和Test不在一個包內;第二,雖然Test是Object的子類,但是不是Test自己調用Object中的protected方法Clone而是調用MyTest的父類的Clone方法。所以沒有protected的訪問權限。

 

再看示例2:

Test2.java

這里,我們在MyObject2類中覆蓋(override)父類的clone()方法,在另一個類Test2中調用clone()方法,編譯通過。

編譯通過的原因顯而易見,當你在MyObject2類中覆蓋clone()方法時,MyObject2類和Test2類在同一個包下,所以此protected方法對Test2類可見。

分析到這里,我們在回憶一下 Java中的淺復制與深復制,章節2.2中的聲明,②在派生類中覆蓋基類的clone()方法,並聲明為public。現在明白這句話的原因了吧(為了讓其它類能調用這個類的clone()方法,重載之后要把clone()方法的屬性設置為public)。

下面再來看示例3:

Test3.java

這里我用Test3類繼承MyObject3,注意這兩個類是不同包的,否則就是示例2的情形。在Test3類中調用Test3類的實例tobj的clone()方法,編譯通過。而同樣調用MyObject3類的實例obj的clone()方法,編譯錯誤!

意想不到的結果,protected方法不是可以被繼承類訪問嗎?

必須明確,類Test3確實是繼承了類MyObject3(包括它的clone方法),所以在類Test3中可以調用自己的clone方法。但類MyObject3的protected方法對其不同包子類Test3來說,是不可見的。

 

這里再給出《java in a nutshell》中的一段話:

protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.

翻譯:protected訪問是需要一些准備的。假如類A定義了一個protected的屬性x,並且被定義在不同包中的類B擴展了類A。A和B不再同一個包內這一點非常重要。從而,B繼承了A的protected屬性x,而且在當前B 的實例中這個屬性是能夠被訪問的又或者其他代碼中涉及到訪問這個屬性的B的實例中也是可以訪問這個屬性的。然而,這並不表示B 的代碼可以任意訪問A的實例中protected修飾的屬性!如果一個對象是A而不是B的實例,顯然B是沒有繼承該對象的屬性的,從而B的代碼無法訪問它們。

 

方法的訪問控制:

 

public

protected

default

private

同類

T

T

T

T

同包

T

T

T

 

子類(不同包)

T

T

 

 

不同包中無繼承關系的類

T

 

 

 

本文對網上一篇文章修改的,增加了自己的理解和注釋。原文地址:http://zhangjunhd.blog.51cto.com/113473/19287/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM