protected 修辞方法引起的错误:The method * from the type * is not visible

一提到访问控制符protected,即使是初学者一般都会很自信的认为自己在这方面的理解没有问题。那好,我们提一个问题出来看看…

问题提出:
   请看下面两端代码,其中包B中的猫和鼠都继承了动物类。

  1. package testa;      
  2. public class Animal {      
  3.     protected void crowl(String c){      
  4.         System.out.println(c);      
  5.     }      
  6. }  

代码2:

  1. package testb;  
  2. import testa.Animal;  
  3.   
  4. class Cat extends Animal   
  5. {    
  6.       
  7. }    
  8. public class Rat extends Animal{    
  9.     public void crowl(){    
  10.               this.crowl("zhi zhi"); //没有问题,继承了Animal中的protected方法——crowl(String)    
  11.               Animal ani=new Animal();  
  12.               ani.crowl("animail jiaojiao"); //wrong, The method crowl(String) from the type Animal is not visible   
  13.               Cat cat=new Cat();    
  14.               cat.crowl("miao miao"); //wrong, The method crowl(String) from the type Animal is not visible    
  15.     }    
  16. }  

既然,猫和鼠都继承了动物类,那么在鼠类的作用范围内,看不到猫所继承的crowl()方法呢?

症结所在:
       protected受访问保护规则是很微妙的。虽然protected域对所有子类都可见。但是有一点很重要,子类只能在自己的作用范围内访问自己继承的那个父类protected,而无法到访问别的子类(同父类的亲兄弟)所继承的protected域和父类对象的protectedani.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 里就可以访问了。

  1. package com;  
  2.   
  3. import testa.Ani;  
  4. class Animail {    
  5.     protected void crowl(String c){    
  6.         System.out.println(c);    
  7.     }    
  8. }    
  9. class Cat extends Animail{    
  10.         
  11. }    
  12. public class Rat extends Animail{    
  13.     public void crowl(){    
  14.                 crowl("zhi zhi"); //没有问题,继承了Animal中的protected方法——crowl(String)   
  15.                 Animail ani=new Animail();  
  16.                 ani.crowl("animail jiaojiao");  
  17.                 Cat cat=new Cat();    
  18.                 cat.crowl("miao miao"); //wrong, The method crowl(String) from the type Animal is not visible    
  19.                 
  20.     }  
  21.       
  22.     public static void main(String[] args){  
  23.         Rat rat=new Rat();  
  24.         rat.crowl();  
  25.     }  
  26. }   
运行结果:
  1. zhi zhi  
  2. animail jiaojiao  
  3. miao miao 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章