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

时间:2013-12-13 17:12:48

标签: java inner-classes access-specifier

我正在阅读Java编程的介绍,它对这个主题没有很好的解释,这让我想知道为什么有人在java中使用私有内部类而不是使用公共内部类。

它们都只能由外层使用。

1 个答案:

答案 0 :(得分:25)

您的声明They both can be used only by the outer class.错误:

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
    }
}

请注意,您实际上可以在另一个类中拥有A.C的实例,并将其称为C(包括其所有公开声明),但不能用于A.B


从这一点你可以理解,你应该使用私有/公共修饰符为内部类通常使用它。