编程语言
首页 > 编程语言> > java – 访问子类对象的私有字段

java – 访问子类对象的私有字段

作者:互联网

刚发现这个结构没有编译:

class A {
    private int data;
    public static int process(B b) {
        return b.data;// error here: 'data has private access in A'
    }
}
class B extends A {}

当然,这个问题可以通过手动轻松解决(将b转换为A,使场保护等).但问题是,为什么java不允许这样的构造?我认为编译器必须知道B是A的子类,因此A的方法必须能够访问A的私有字段.

我能想到的唯一可能的问题是,如果B有自己的’数据’字段,编译器必须不知道我们想要访问哪个字段,但那是继承的用途,对吧?

解决方法:

好吧,编译器不允许它,因为语言规范不允许它. JLS section 8.3(字段声明)指定(强调我的):

A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

A private field of a superclass might be accessible to a subclass – for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.

因此,将该字段作为子类(6.5.6.2)的成员查找必须失败 – 编译器在解释为什么它失败而不仅仅是说该成员不存在时略有帮助,但我相信在纯粹意义上,查找应该是只是说“B型没有一个叫做数据的成员”而不是抱怨它不可访问.

至于为什么语言是这样设计的 – 我不确定. C#中的等效代码很好,对我来说很有意义.例如,在C#5规范中,第3.4节:

When a type inherits from a base class, all members of the base class, except instance constructors, destructors and static constructors, become members of the derived type. The declared accessibility of a base class member does not control whether the member is inherited—inheritance extends to any member that isn’t an instance constructor, static constructor, or destructor. However, an inherited member may not be accessible in a derived type, either because of its declared accessibility (§3.5.1) or because it is hidden by a declaration in the type itself (§3.7.1.2).

标签:java,inheritance,subclass,private-members
来源: https://codeday.me/bug/20190708/1403432.html