What are the purposes of inner classes

user962206 picture user962206 · Jul 9, 2012 · Viewed 34.3k times · Source

I am reviewing the concept of inner classes in java. so far from what I've understood and applied java inner classes has a link or access to the methods and fields of its outer/ enclosing class.

My Question:

  1. When should create or define an inner class?
  2. are inner classes considered to be called as "Helper classes" ?
  3. What are the indicators for you to make an inner class and what's their other purpose?

Answer

kosa picture kosa · Jul 9, 2012

Inner classes are best for the purpose of logically grouping classes that are used in one-place. For example, if you want to create class which is used by ONLY enclosing class, then it doesn't make sense to create a separate file for that. Instead you can add it as "inner class"

As per java tutorial:

Compelling reasons for using nested classes include the following:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • It can lead to more readable and maintainable code.