Last Modified 2019.2.1

Nested Classes

The Java programming language allows you to define a class within another class. Such a class is called a nested class.

class OuterClass {

  class NestedClass {
    //...
  }

}

Nested classes are a member of the outer class. As a member of the outer class, nested classes can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private) Nested classes have two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. Inner classes have access to instance variables or instance methods --even if they are declared private-- of the outer class. Static nested classes do not have access to instance variables or instance methods of the outer class.

class OuterClass {

  static class StaticNestedClass {
    //...
  }

  class InnerClass {
    //...
  }

}

Like static variables or methods, static nested classes cannot refer directly to instance variables or methods defined in outer class.

Why Use Nested Classes?

  • Increases encapsulation
  • More readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

The following code snippets from the ArrayList<E> class show an excellent example of Nested classes.

public Iterator<E> iterator() {
  return new Itr();
}

private class Itr implements Iterator<E> {
  //...
}

Anonymous Classes

The life cycle of the method and its local variables is the same. The life cycle of inner classes is longer than the one of methods. Therefore, Java restricts anonymous classes defined in a method only to use the final local variables of the method.

References