日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA访问控制符(写给初学者的)

發(fā)布時(shí)間:2025/3/21 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA访问控制符(写给初学者的) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

protected訪7問修飾符表示如果兩個(gè)類在同一個(gè)包中,那么被修飾為protected方法或?qū)傩钥梢员黄渌念愃L問。?
但是如果兩個(gè)類不在同一個(gè)包中,被修飾為protected的類只能被有繼承關(guān)系的類(子類)所訪問;沒有繼承關(guān)系的類不能訪問。?

public (友好)是限制級(jí)最小的,只要被修飾為public ,不管是不是同一個(gè)包,或者同一個(gè)類,有沒有繼承關(guān)系都可以被訪問。

?一般來說 訪問控制分4種級(jí)別:

公開:public 同類 同包 子類 不同包 都可以訪問
默認(rèn):只向同包同類放開
私有:private 只有類本身可以訪問
保護(hù):protected 向子類以及同一個(gè)包中的類放開?


來看一下在該節(jié)中的例子
先定義一個(gè)ClassA 并把它放在mypack1包中

package 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;
}
}


然后又在另外一個(gè)包 mypackage2中 存在ClassA的一個(gè)子類 ClassC

package mypack2;
import mypack1.ClassA;
class ClassC extends mypack1.ClassA{
public void method(){
ClassA a = new ClassA();
a.var1=1;
a.var2=1; //此行出錯(cuò)
}?
}


實(shí)際上這個(gè)例子有問題
你會(huì)看到ide(或者編譯時(shí))在 a.var2=1 這一行報(bào)錯(cuò) 提示不能訪問protected對(duì)象
這就是protected經(jīng)常被人忽視的地方
盡管ClassC是ClassA的一個(gè)子類
但是在ClassC中創(chuàng)建的是ClassA的一個(gè)實(shí)例
該實(shí)例中的protected成員變量則很明顯沒有被ClassC繼承到
自然在ClassC中無法訪問var2

所以對(duì)于這種情況 將代碼改為如下,則可以編譯通過。

package mypack2;
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访问控制符(写给初学者的)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。