2013-03-17 246 views
2

我有以下兩種一段代碼:保護訪問修飾符

/** 
* 
*/ 
package com.akshu.multithreading; 

/** 
* @author akshu 
* 
*/ 
public class MyThread extends Thread { 
    protected int b; 

    private int a; 
    @Override 
    public void run() { 

     super.run(); 

     System.out.println("int a:"+a); 
    } 

} 



----------- 


package com.akshu.utility; 

import com.akshu.multithreading.MyThread; 

public class MyUtility extends MyThread{ 

    public static void main(String args[]) 
    { 
     MyThread th1 = new MyThread(); 
     int d =th1.b; // line1 
     System.out.println("int d"+d); 
    } 

} 

與上面的代碼文件,我想了解保護的訪問修飾符的目的。在文件MyUtility,我想引用類的變量b MyThread.But它給我下面的錯誤:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The field MyThread.b is not visibilty. 

我關心的是變量b應該從子類訪問,因爲我已經延長了MyThread的。但它給我編譯時錯誤。另外當我在我的超類中聲明這個變量爲靜態時,我能夠直接訪問它。所以當我試圖通過實例訪問時,我在做什麼錯?

回答

2

方法main不是MyThread的顯式部分 - 如果要實現另一個函數,例如prtintB(),你可以使用直接訪問「。」運營商。要從主體訪問它,你必須編寫一個getter函數。

2

您無法從實例訪問受保護的屬性。你只能在繼承類中訪問它們。在這種LINE-

MyThread th1 = new MyThread(); int d = th1 . b ; 

你實際上是試圖從一個實例th1訪問受保護的財產。

+0

OP實際上是試圖從一個實例'th1'訪問aprotected財產。 – ShuklaSannidhya 2013-03-17 14:15:08

+0

:謝謝,我明白你的意思了。我把兩種不同的可見度混合在一起。一個例如和其他的繼承。 – noone 2013-03-17 14:39:08

2

Kathy Sierra's偉大的書,解釋protected範圍的誤解:

But what does it mean for a subclass-outside-the-package to have access to a superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. Protected does not mean that the subclass can treat the protected superclass member as though it were public. So if the subclass-outside-the-package gets a reference to the superclass (by, for example, creating an instance of the superclass somewhere in the subclass' code), the subclass cannot use the dot operator on the superclass reference to access the protected member. To a subclass-outside-the-package, a protected member might as well be default (or even private), when the subclass is using a reference to the superclass. The subclass can see the protected member only through inheritance.

因此,你的情況,你嘗試使用引用來訪問受保護的成員父母的類包的外部:

MyThread th1 = new MyThread(); 
int d =th1.b; //b cannot be reached ! 
1

Java lang規範第6.6.2.1節會告訴你實話:

If the access is by a field access expression E.Id , where E is a Primary expression, or by a method invocation expression E.Id(. . .) , where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S .

這裏MyThreadC, MyUtilityS和b是Id。因此,在一個MyUtility ionstance你不能用一個參考實例PF MyThread訪問其b