首先我們來看一下如下兩個示例:
示例一:
//包A中有一個動物類 package testa; public class Animal { protected void crowl(String c){ System.out.println(c); } }
(視頻教程推薦:java視頻)
示例二:
package testb; import testa.Animal; class Cat extends Animal { } public class Rat extends Animal{ public void crowl(){ this.crowl("zhi zhi"); //沒有問題,繼承了Animal中的protected方法——crowl(String) Animal ani=new Animal(); ani.crowl("animail jiaojiao"); //wrong, The method crowl(String) from the type Animal is not visible Cat cat=new Cat(); cat.crowl("miao miao"); //wrong, The method crowl(String) from the type Animal is not visible } }
既然,貓和鼠都繼承了動物類,那么在鼠類的作用范圍內(nèi),看不到貓所繼承的crowl()方法呢?
問題解答:
protected受訪問保護規(guī)則是很微妙的。雖然protected域?qū)λ凶宇惗伎梢姟5怯幸稽c很重要,不同包時,子類只能在自己的作用范圍內(nèi)訪問自己繼承的那個父類protected域,而無法到訪問別的子類(同父類的親兄弟)所繼承的protected域和父類對象的protected域ani.crow1()。 說白了就是:老鼠只能叫"zhi,zhi"。即使他能看見貓(可以在自己的作用域內(nèi)創(chuàng)建一個cat對象),也永遠無法學會貓叫。
也就是說,cat所繼承的crowl方法在cat類作用范圍內(nèi)可見。但在rat類作用范圍內(nèi)不可見,即使rat,cat是親兄弟也不行。
另外: 這就是為什么我們在用clone方法的時候不能簡單的直接將對象aObject.clone()出來的原因了。而需要在aObject.bObject=(Bobject)this.bObject.clone();
總結(jié):
當B extends A的時候,在子類B的作用范圍內(nèi),只能調(diào)用本子類B定義的對象的protected方法(該方法從父類A中繼承而來)。而不能調(diào)用其他A類(A 本身和從A繼承)對象的protected方法。
推薦教程:java入門程序