浅谈java protected关键字

前提:不在同一个包下,在同一个包下就变成package level的访问了,性质不一样
结论:只能访问自己继承的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.

参考: http://zhangjunhd.blog.51cto.com/113473/19287


随便写了点示例
package pTest.pkg1;

public class SuperClass {
	protected int x;
}

package pTest.pkg1;

public class SubClassA extends SuperClass {

	void printX(){
		System.out.println(x);
	}
}

package pTest.pkg2;

import pTest.pkg1.SubClassA;
import pTest.pkg1.SuperClass;

public class SubClassB extends SuperClass {
	public static void main(String[] args) {
		SubClassB b = new SubClassB();
		System.out.println(b.x);
		SubClassA a = new SubClassA();
//		System.out.println(a.x);
		SuperClass s = new SuperClass();
//		System.out.println(s.x);
		
	}
}


把注释去掉,即可看到报错信息

the field SuperClass.x is not visible

你可能感兴趣的:(java,Blog,Access)