A Restriction on Protected Access

<p><span style="font-size:14px;">假设类D继承自类B,类B中有一个protected的成员属性n,并且类D和类B在不同的包中,所以类D和类B如下定义:</span></p>
<span style="font-size:14px;">package one;
public class B
{
        protected int n;
        ...
}

package two;
import  one.B;
public class D extends B
{
       ....
}</span>
然后D中便可以出现如下方法:

<span style="font-size:14px;">public void demo()
{
       n = 42;
}</span>

也可以像下面这样:

<span style="font-size:14px;">public void demo2()
{
       D object = new D();
       object.n = 42;
}</span>

但是不能出现下面的方法:

<span style="font-size:14px;">public void demo3()
{
        B object = new B();
        object.n = 42;
}</span>

编译器会给出一个错误信息说n在B中是被保护的。protected的成员方法同样如此。

A class can access its own classes’ inherited variables and methods that are marked
protected in the base class, but cannot directly access any such instance variables or
methods of an object of the base class (or of any other derived class of the base class). In
the above example, n is an instance variable of the base class B and an instance variable of
the derived class D. D can access n whenever n is used as an instance variable of D, but D
cannot access n when n is used as an instance variable of B.http://www.tanhuanyao.com   http:// tanhuanyao.com   http://www.bianshayao.com/   http://bianshayao.com/
If the classes B and D are in the same package, you will not get the error message
because, in Java, protected access implies package access. In particular, if the classes B and
D are both in the default package, you will not get the error message.

     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值