What are the purposes of inner classes

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?

Solution 1:

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.

Solution 2:

A classic use for an inner class is the implementation of an iterator inside a container (ArrayList, for example - look for class Itr). All the container wants to expose to the rest of the world is an Iterator. However, it has to create some concrete implementation of that iterator, possibly familiar with the internals of the container. Using an inner class hides the implementation, while keeping it close to the container's implementation. And being inner (i.e. non-static), it is bound to a specific instance of that container, which lets it access private container members.

There are a few types of inner classes - non-static nested class, local classes and anonymous classes. Each one has a somewhat different purpose, so when asking about an inner class, you should specify what kind are you talking about.

Assuming you're referring to non-static inner classes, I'd say the reason to use them is the same as using regular classes (namely abstraction and dividing code into logical units), but there's no reason to make this use of classes visible to the rest of the world. You can also make nested classes public, of course, in which case you'd make them nested instead of independent in order to express their tight relation with the outer class.

Solution 3:

  1. See the Java tutorial for the main reasons.

  2. If by "helper class" you mean something for internal use only, then no, not necessarily. You might want to do something like

    class Outer {
        private static class Inner implements InterestingInterface {
            // whatever
        }
        public InterestingInterface make_something_interesting() {
            return new Inner();
        }
    }
    

    Here, Inner is not a "helper class" in the sense that the outside world does get to see instances of it, but its implementation is entirely hidden -- the outside world only knows it gets some object that implements InterestingInterface.

Solution 4:

As a general rule, objects should be designed for a single responsibility (Highly cohesive). In other words, any object designed well, should perform a single coherent task. This would be considered best practice for object orientated design.

Sometimes, however, a developer may design a class that requires a separate specialized class in order to work. This separate specialized class could be considered a helper class.

If the helper class is not used by any other class, then it would be considered a prime candidate as an inner class

As elicited by ncmathsadist above, an example of inner class use would be in the implementation of Event handlers.

For example, in designing a graphical user interface (GUI), a developer may have created a button that performs a particular task after the user presses it.

The button would need an event handler which listens for when that particular button is pressed.

In this case, creating the event handler for the button as an inner class would be best practice as the inner class would not be utilized anywhere else other than with the specific button within the GUI class.

Solution 5:

One purpose of inner classes is to attach listeners. For example, suppose you have a JMenuItem. You can make it quit your app as shown in this code:

JMenuItem quitItem = new JMenuItem("Quit");
quitItem.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
        //cleanup code before exiting
        System.exit(0);
    }
});

You may also want a class to have access to outer class state variables which is entirely subservient to that class. For example, consider writing a simple color calculator. It might have a text area into which you type a hex code. When you hit enter, you want a JPanel to display the color. Here is a crude outline of what you might do.

public class ColorCalc extends JPanel implements Runnable
{
    Color displayedColor;
    JTextArea colorEnterArea;
    public ColorCalc()
    {
        displayedColor = Color.white
        colorEnterArea = new JTextArea();
    }
    public void run()
    {
        //build GUI here
    }
    public static void main(String[] args)
    {
         ColorCalc cc = new ColorCalc();
         javax.swing.SwingUtilities.invokeLater(cc);
    }
    //subservient inner class with access to outer class state variable.
    class ColorPanel extends JPanel
    {
         public void paintComponent(Graphics g)
         {
             g.setColor(displayedColor);
             g.fillRect(0,0,getWidth(), getHeight());
         } 
    }

}