简体   繁体   English

打破Java中的封装和信息隐藏

[英]Breaking encapsulation and information hiding in Java

Consider the following snippet. 请考虑以下代码段。

package breakoop;

public class BreakOOP {

    public static class A{
        private int a;
    }

    public static class B extends A{
        public int f(){
            return super.a;
        }
    }

    public static void main(String[] args) {
        B b = new B();
        System.out.println(b.f());
    }
}

The example only compiles if A and B are encapsulated within the BreakOOP class. 该示例仅在AB封装在BreakOOP类中时才编译。

This seems to go against some of the fundamental concepts of OOP. 这似乎违背了OOP的一些基本概念。 Can someone explain why this compiles? 有人可以解释为什么这个编译? What is the reasoning behind it? 它背后的原因是什么?

Check this: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html . 请查看: https//docs.oracle.com/javase/tutorial/java/javaOO/nested.html It says it increases encapsulation by allowing the static class to access private members of the top level class (sometimes you may need to do that). 它说它通过允许static类访问顶级类的私有成员来增加封装(有时你可能需要这样做)。 And a is private member of class A , which is in the scope of BreakOOP , which in turn makes it accessible inside class B . 并且aAA私有成员,它属于BreakOOP的范围,后者又可以在B类中访问它。

The Java Language Specification states: Java语言规范声明:

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. 私有类成员或构造函数只能在顶级类(第7.6节)的主体内访问,该类包含成员或构造函数的声明。

Since classes A and B are defined within the body of BreakOOP that rule applies and B can see private members of A . 由于A类和B类是在BreakOOP的主体内定义的, BreakOOP规则适用, B可以看到A私有成员。

As for the OOP concepts: since A and B are static inner classes they don't have the special life-cycle relation with BreakOOP that true inner classes have (ie you don't need an instance of BreakOOP to create a new instance of A or B but they still have a somewhat special relation in that they have access to private members. If they should not have that kind of relationship then they shouldn't be inner classes but true top level classes. 至于OOP概念:由于AB是静态内部类,因此它们与真正的内部类具有的BreakOOP没有特殊的生命周期关系(即,您不需要BreakOOP的实例来创建A的新实例或B ,但他们仍然有他们有权访问私有成员有些特殊的关系。如果他们不应该有那种关系,那么他们不应该是内部类,但真正的顶级类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM