学过java的都知道,protected的访问权限对子类来说,无论在包里还是保外都能访问的,真实情况是什么样的呢?同包下的子类继承就不研究了,主要看下不同包下的子类
父类:
package com.father;
public class Father1 {
String name;
public int age;
protected String color;
}
子类:
package com.son;
import com.father.Father1;
public class Son extends Father1{
public static void main(String[] args) {
String c;
// TODO Auto-generated method stub
Father1 f = new Father1();
c = f.color;//无法访问,报错
Father1 f = new Son();
c = f.color;//无法访问,报错
Son s = new Son();
c = s.color;//正常
}
}
在Son类中新建个副类:
class Son2 extends Son{
public static void main(String[] args) {
String c;
Son s = new Son2();
c = s.color;//无法访问,报错
Son2 s2 = new Son2();
c = s2.color;//正常
}
由此可以看出只能是子类自己的实例对象才能访问父类protected,其他的都不能访问
这里再给出《java in a nutshell》中的一段话:
protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.