protected的使用注意事项针对继承关系的可继承性

package 1
class MyObject3 {
protected Object clone() throws CloneNotSupportedException {
       return super.clone();
    }
}
 
package 2
public class Test3 extends MyObject3 {
    public static void main(String args[]) {
       MyObject3 obj = new MyObject3();
       obj.clone(); // Compile error.
       Test3 tobj = new Test3();
       tobj.clone();// Complie OK.
    }
}
这里我用Test3类继承MyObject3,注意这两个类是不同包的,否则就是示例2的情形。在Test3类中调用Test3类的实例tobj的clone()方法,编译通过。而同样调用MyObject3类的实例obj的clone()方法,编译错误!
意想不到的结果,protected方法不是可以被继承类访问吗?
必须明确,类Test3确实是继承了类MyObject3(包括它的clone方法),所以在类Test3中可以调用自己的clone方法。但类MyObject3的protected方法对其不同包子类Test3来说,是不可见的。
这里再给出《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.
顺便说两句,国内的很多Java书籍在介绍访问权限时,一般都这样描述(形式各异,内容一致):
方法的访问控制:
 
public
protected
default
private
同类
T
T
T
T
同包
T
T
T
 
子类(不同包)
T
T
  
不同包中无继承关系的类
T
   
 
posted on 2012-08-08 16:15 moonfans 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/moonfans/archive/2012/08/08/2628485.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值