When to use inner classes in Java for helper classes

Hild picture Hild · Aug 23, 2013 · Viewed 51.7k times · Source

If I have for example a class along with a helper class to do some of its functionality, does it make sense to make it as an inner class.

    public class Foo {
       private FooHelper helper;

       // constructor & any other logic

       public void doSomeThing() {
         helper.do();
       }
    }

    public class FooHelper {
        public void do() {
         // code
        }
    }

In the above case does it make sense to make the FooHelper as an inner class ? Apology if this sound stupid but I am little confused about the use cases.

Answer

MD Sayem Ahmed picture MD Sayem Ahmed · Aug 23, 2013

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.