Public vs Private Inner Classes in Java

I read an introduction to Java programming and it does not have a good explanation for this topic, and this made me wonder why someone should use a private inner class in java instead of using a public one.

Both of them can be used only by an external class.

+8
java inner-classes access-specifier
source share
1 answer

Your statement They both can be used only by the outer class. 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(); AB b = a.getB(); //cannot compile AC c = a.getC(); //compiles perfectly } } 

Please note: in fact, you can have an AC instance in another class and refer to it as C (including all its public declarations), but not AB .


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

+22
source share

All Articles