简体   繁体   English

Java中的公共内部类和私有内部类

[英]Public vs Private inner classes in Java

I was reading introduction to Java programming and it does not have a good explanation regarding this topic and it made me wonder why should someone use a private inner class in java instead of using a public one. 我正在阅读Java编程的介绍,它没有关于这个主题的很好的解释,它让我想知道为什么有人在java中使用私有内部类而不是使用公共内部类。

They both can be used only by the outer class. 它们都只能由外层使用。

Your claim They both can be used only by the outer class. 你的主张They both can be used only by the outer class. is wrong: 是错的:

public class A {
    private class B {}
    public class C {}
    public C getC() { 
        return new C();
    }
    public B getB() {
        return new B();
    }

}
public class Tryout {
    public static void main(String[] args) {
        A a = new A();
        A.B b = a.getB(); //cannot compile
        A.C c = a.getC(); //compiles perfectly
    }
}

Note that you can actually have an instance of AC in another class and refer to it as C (including all its public declaration), but not for AB . 请注意,您可以在另一个类中实际拥有AC实例,并将其称为C (包括其所有公开声明),但不是AB


From this you can understand, you should use private/public modifier for inner classes the same way you use it generally. 从中你可以理解,你应该使用私有/公共修饰符来内部类,就像你通常使用它一样。

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

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