銆銆Test.java
class MyObject {}
public class Test {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.clone(); // Compile error.
}
}
銆銆姝ゆ椂鍑虹幇涓婃枃鎻愬埌鐨勯敊璇細The method clone from the type Object is not visiuable.
銆銆鍚屾牱Test涔熸槸java.lang.Object鐨勫瓙綾匯備絾鏄紝涓嶈兘鍦ㄤ竴涓瓙綾諱腑璁塊棶鍙︿竴涓瓙綾葷殑protected鏂規硶錛屽敖綆¤繖涓や釜瀛愮被緇ф壙鑷悓涓涓埗綾匯?/p>
銆銆鍐嶇湅紺轟緥2錛?/p>
銆銆Test2.java
class MyObject2 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test2 {
public static void main(String[] args) throws CloneNotSupportedException {
MyObject2 obj = new MyObject2();
obj.clone(); // Compile OK.
}
}
銆銆榪欓噷錛屾垜浠湪MyObject2綾諱腑瑕嗙洊錛坥verride錛夌埗綾葷殑clone錛堬級鏂規硶錛屽湪鍙︿竴涓被Test2涓皟鐢╟lone錛堬級鏂規硶錛岀紪璇戦氳繃銆?/p>
銆銆緙栬瘧閫氳繃鐨勫師鍥犳樉鑰屾槗瑙侊紝褰撲綘鍦∕yObject2綾諱腑瑕嗙洊clone錛堬級鏂規硶鏃訛紝MyObject2綾誨拰Test2綾誨湪鍚屼竴涓寘涓嬶紝鎵浠ユprotected鏂規硶瀵筎est2綾誨彲瑙併?/p>
鍒嗘瀽鍒拌繖閲岋紝鎴戜滑鍦ㄥ洖蹇嗕竴涓婮ava涓殑嫻呭鍒朵笌娣卞鍒舵枃涓紝绔犺妭2.2涓殑澹版槑錛屸憽鍦ㄦ淳鐢熺被涓鐩栧熀綾葷殑clone()鏂規硶錛屽茍澹版槑涓簆ublic銆? 鐜板湪鏄庣櫧榪欏彞璇濈殑鍘熷洜浜嗗惂錛堜負浜嗚鍏跺畠綾昏兘璋冪敤榪欎釜綾葷殑clone()鏂規硶錛岄噸杞戒箣鍚庤鎶奵lone()鏂規硶鐨勫睘鎬ц緗負public錛夈?/p>
銆銆涓嬮潰鍐嶆潵鐪嬬ず渚?錛?/p>
銆銆Test3.java
package 1
class MyObject3 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
銆銆package 2
public class Test3 extends MyObject3 {
public static void main(String args[]) {
MyObject3 obj = new MyObject3();
obj.clone(); // Compile error.
Test3 tobj = new Test3();
tobj.clone();// Complie OK.
}
}
銆銆榪欓噷鎴戠敤Test3綾葷戶鎵縈yObject3錛屾敞鎰忚繖涓や釜綾繪槸涓嶅悓鍖呯殑錛屽惁鍒欏氨鏄ず渚?鐨勬儏褰€傚湪Test3綾諱腑璋冪敤Test3綾葷殑瀹炰緥tobj鐨刢lone錛堬級鏂規硶錛岀紪璇戦氳繃銆傝屽悓鏍瘋皟鐢∕yObject3綾葷殑瀹炰緥obj鐨刢lone錛堬級鏂規硶錛岀紪璇戦敊璇紒
銆銆鎰忔兂涓嶅埌鐨勭粨鏋滐紝protected鏂規硶涓嶆槸鍙互琚戶鎵跨被璁塊棶鍚楋紵
銆銆蹇呴』鏄庣‘錛岀被Test3紜疄鏄戶鎵夸簡綾籑yObject3錛堝寘鎷畠鐨刢lone鏂規硶錛夛紝鎵浠ュ湪綾籘est3涓彲浠ヨ皟鐢ㄨ嚜宸辯殑clone鏂規硶銆備絾綾籑yObject3鐨刾rotected鏂規硶瀵瑰叾涓嶅悓鍖呭瓙綾籘est3鏉ヨ錛屾槸涓嶅彲瑙佺殑銆?/p>
銆銆榪欓噷鍐嶇粰鍑恒妀ava in a nutshell銆嬩腑鐨勪竴孌佃瘽錛?/p>
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.
銆銆欏轟究璇翠袱鍙ワ紝鍥藉唴鐨勫緢澶欽ava涔︾睄鍦ㄤ粙緇嶈闂潈闄愭椂錛屼竴鑸兘榪欐牱鎻忚堪錛堝艦寮忓悇寮傦紝鍐呭涓鑷達級錛?/p>
銆銆鏂規硶鐨勮闂帶鍒訛細
public | protected | default | private | |
鍚岀被 | T | T | T | T |
鍚屽寘 | T | T | T | |
瀛愮被(涓嶅悓鍖? | T | T | ||
涓嶅悓鍖呬腑鏃犵戶鎵垮叧緋葷殑綾?/td> | T |
銆銆鏈枃鍑鴻嚜 “瀛?瀛?#8221; 鍗氬錛岃鍔″繀淇濈暀姝ゅ嚭澶刪ttp://zhangjunhd.blog.51cto.com/113473/19287