14

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.

They both can be used only by the outer class.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Lind
  • 233
  • 1
  • 5
  • 14

1 Answers1

34

Your claim 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 A.C in another class and refer to it as C (including all its public declaration), but not for A.B.


From this you can understand, you should use private/public modifier for inner classes the same way you use it generally.

amit
  • 175,853
  • 27
  • 231
  • 333