Java:超类对象上子类的受保护访问限制 [英] Java : Protected access restriction for subclass on superclass object

查看:110
本文介绍了Java:超类对象上子类的受保护访问限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在此论坛之前已经提到过这个问题,但我会再次提问,因为我没有看到任何好的答案(到目前为止)。

I know that this has been asked before in this forum but i will ask again since i don't see any good answer (so far).

这里有去:

package a;
public class A{
    protected int a;
}

package b;
public class B extends A{
}

package c;
public class C extends B{
    public void accessField(){
        A ancient = new A();
        ancient.a = 2;  //A - That wouldn't work.

        a = 2;   //B - That works.
    }

}

为什么条款A)不会工作?在子类C中对超类对象古代访问的限制背后的理性是什么?

谢谢。

Why clause A) won't work? What's the rational behind this restriction on superclass object ancient access in subclass C?
Thanks.

推荐答案

受保护成员只能通过继承访问同一个包之外 - 即在层次结构中。

Protected members can only be accessed outside of the same package if it's via inheritance - i.e. within the hierarchy.

所以当你从另一个包中创建另一个A实例时,这不是继承关系,因此失败。

So when you're creating another instance of A from a different package, that's not an inheritance relationship and it thus fails.

与往常一样,这在JLS,6.6.2中有所涉及:

As always, this is covered in the JLS, 6.6.2:


对象的受保护成员或构造函数可以从包外部访问,只能通过负责实现该对象的代码来声明它。

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

这篇关于Java:超类对象上子类的受保护访问限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆