问题提出:
请看下面两端代码,其中包B中的猫和鼠都继承了动物类。
- package testa;
- public class Animal {
- protected void crowl(String c){
- System.out.println(c);
- }
- }
代码2:
- 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方法
另外:同包内均和派生类中可比默认[default|package](只包内能使用) 权限大一点。
如把上面代码放到同一package 里就可以访问了。
- package com;
- import testa.Ani;
- class Animail {
- protected void crowl(String c){
- System.out.println(c);
- }
- }
- class Cat extends Animail{
- }
- public class Rat extends Animail{
- public void crowl(){
- crowl("zhi zhi"); //没有问题,继承了Animal中的protected方法——crowl(String)
- Animail ani=new Animail();
- ani.crowl("animail jiaojiao");
- Cat cat=new Cat();
- cat.crowl("miao miao"); //wrong, The method crowl(String) from the type Animal is not visible
- }
- public static void main(String[] args){
- Rat rat=new Rat();
- rat.crowl();
- }
- }
- zhi zhi
- animail jiaojiao