您的位置:首页 > 其它

你以为你的protected控制访问符理解透彻了吗

2016-04-30 11:14 225 查看
最近做了个项目出现下面的问题:

好吧直接引用:

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

问题提出:

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


[java]
view plain
copy

package testa;
public class Animal {
protected void crowl(String c){
System.out.println(c);
}
}

代码2:

[java]
view plain
copy

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对象),也永远无法学会猫叫但是父类和他们在同一个包中就可以通过ani和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方法

另外:protected可以被他的子类访问(但是只在子类范围内)和同一个包中访问 权限大一点。
如把上面代码放到同一package 里就可以访问了。

[java]
view plain
copy

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();
}
}

运行结果:

[java]
view plain
copy

zhi zhi
animail jiaojiao
miao miao
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: