Inner Classes

An inner class is a class declared within another class. These classes are declared exactly as the classes that we know and they have their own code.

And why create an inner class instead a normal class? Here are some of the reasons:

  • To access at the private fields of a class from other class.
  • To hide a class from other class of the same package.
  • To create internal anonymous class. They are so useful to manage events.
  • When just a class may access to the fields of the other class.

Let’s see an easy example of inner classes:

The class student has an object as attribute, Address. We define the class for this object in the same class, as an inner class. The class Address has its own fields and method.

The most common use of inner classes are the anonymous inner classes. Let’s see an example declaring a Thread and then let’s see how them work:

What are we doing there? It’s easy. We are defining the method run from the new object Runnable that we’ve create. On this way we don’t have to create new class that implements Runnable, override it method run and then create a new object from this class. We just create a new Runnable object as a parameter of Thread and there we redefine the method run.

This is very used in listener for button or other elements of the graphic interface. Imagine if we had to create a new class to redefine the listener of each button or menu item in our interface, we would have too many classes.

Notice that to redefine an existent class, we have to use the constructor as usually and then we open a curly brace and then write the method that we want to redefine. In this case the expression ends with ); because the Runnable object was inside of the constructor of Thread. This will be usually the form that you will find inner class, calling constructors or methods.