JAVA访问控制符(写给初学者的)
protected訪7問修飾符表示如果兩個類在同一個包中,那么被修飾為protected方法或?qū)傩钥梢员黄渌念愃L問。?
但是如果兩個類不在同一個包中,被修飾為protected的類只能被有繼承關(guān)系的類(子類)所訪問;沒有繼承關(guān)系的類不能訪問。?
public (友好)是限制級最小的,只要被修飾為public ,不管是不是同一個包,或者同一個類,有沒有繼承關(guān)系都可以被訪問。
?一般來說 訪問控制分4種級別:
默認:只向同包同類放開
私有:private 只有類本身可以訪問
保護:protected 向子類以及同一個包中的類放開?
來看一下在該節(jié)中的例子
先定義一個ClassA 并把它放在mypack1包中
public class ClassA {
public int var1;
protected int var2;
int var3;
private int var4;
public void method(){
var1=1;
var2=1;
var3=1;
var4=1;
ClassA a = new ClassA();
a.var1=1;
a.var2=1;
a.var3=1;
a.var4=1;
}
}
然后又在另外一個包 mypackage2中 存在ClassA的一個子類 ClassC
import mypack1.ClassA;
class ClassC extends mypack1.ClassA{
public void method(){
ClassA a = new ClassA();
a.var1=1;
a.var2=1; //此行出錯
}?
}
實際上這個例子有問題
你會看到ide(或者編譯時)在 a.var2=1 這一行報錯 提示不能訪問protected對象
這就是protected經(jīng)常被人忽視的地方
盡管ClassC是ClassA的一個子類
但是在ClassC中創(chuàng)建的是ClassA的一個實例
該實例中的protected成員變量則很明顯沒有被ClassC繼承到
自然在ClassC中無法訪問var2
所以對于這種情況 將代碼改為如下,則可以編譯通過。
import mypack1.ClassA;
class ClassC extends mypack1.ClassA{
public void method(){
ClassA a = new ClassA();
a.var1=1;
super.var2=1;
ClassC c = new ClassC();
c.var1=1;
c.var2=1;
}
}
OK,用Java?in a nutshell中的一段話來總結(jié)一下全文:
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.
from:?http://blog.csdn.net/it_man/article/details/1453056
總結(jié)
以上是生活随笔為你收集整理的JAVA访问控制符(写给初学者的)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 单例模式探讨
- 下一篇: hiernate的锁机制