Since an enclosing class can access the private fields of its inner class, when should be they declared private, default or public for a private inner class?
At first glance, it seems irrelevant to specify an access modifier on the members of inner classes. As you pointed out, the containing class can access all members anyway.
Here are a few additional considerations though:
public
and serve as part of the interface definition of the containing class. Perhaps the outer class has a method that returns an instance of the inner class. In this case, the inner class is subject to the same best practices for member visibility as top-level classes. It's preferrable to keep implementation details private
in this case.private
can document for future maintainers that those members are not intended to be accessed directly by the outer class code. Of course, at that point, it might warrant refactoring the inner class to its own top-level class.public
members. For example, the Jackson JSON serializer by default only operates on public
members. It is possible to make it operate on private
members by doing a few things like adding a public
getter. This is extra work, so it may be more convenient to declare the member public
in the first place.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With