首先我们来看一下如下两个示例:
示例一://包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
}
}
既然,猫和鼠都继承了动物类,那么在鼠类的作用范围内,看不到猫所继承的crowl()方法呢?
问题解答:
protected受访问保护规则是很微妙的。虽然protected域对所有子类都可见。但是有一点很重要,不同包时,子类只能在自己的作用范围内访问自己继承的那个父类protected域,而无法到访问别的子类(同父类的亲兄弟)所继承的protected域和父类对象的protected域ani.crow1()。说白了就是:老鼠只能叫"zhi,zhi"。即使他能看见猫(可以在自己的作用域内创建一个cat对象),也永远无法学会猫叫。
也就是说,cat所继承的crowl方法在cat类作用范围内可见。但在rat类作用范围内不可见,即使rat,cat是亲兄弟也不行。
另外: 这就是为什么我们在用clone方法的时候不能简单的直接将对象aObject.clone()出来的原因了。而需要在aObject.bObject=(Bobject)this.bObject.clone();
总结:
当B extends A的时候,在子类B的作用范围内,只能调用本子类B定义的对象的protected方法(该方法从父类A中继承而来)。而不能调用其他A类(A 本身和从A继承)对象的protected方法。