浅谈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.

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


随便写了点示例
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值