When to use inner classes in Java for helper classes

From JAVA SE Docs

Why Use Nested Classes?

It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

So Yes, it makes sense to use FooHelper as an inner class.


Yes, it makes perfect sense to make it an inner class. If no other classes need it, make it private. If it doesn't require exclusive access to the members of the outer class, make it a static nested class because then it will require less memory space.

Check out the recommendation from the official tutorial -

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.


Here are some uses of inner classes.

  • Inner classes are used to get functionality which can get an object better than method.
  • They can be used in the case when a set of multiple operations are required and chances of reusability are good inside the class and they will not be accessed but methods outside the outer class.
  • Inner classes are made to achieve multiple inheritance also.
  • Inner classes are used when they are useful in class context.
  • They are used to separate logic inside classes.

So if you have some requirement matching above points than inner classes can be used. It is always better to make inner class private to prevent access from other classes. In your case use of inner classes is helpful to make code readable and separate logic in the outer class.


If you think that FooHelper will not at all be useful for other classes than Foo, then it makes sense to make it as private inner class of Foo. One example of this kind of design can be found in HashMap where it defines a private inner class KeySet

Otherwise having it as a private instance looks good.