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 and is illustrated here:

class OuterClass {

	class NestedClass {


A nested class is a member of its enclosing class.
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Static nested classes do not have access to other members of the enclosing class.
As a member of the OuterClass, a nested class can be declared private, public, protected, or package private.
(Recall that outer classes can only be declared public or package private.)

Nested classes are divided into 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.

class OuterClass {

	static class StaticNestedClass {

	class InnerClass {


As with class methods and variables, a static nested class is associated with its outer class.
And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.

Why Use Nested Classes?

  • If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.
  • It increases encapsulation:By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

The following code snippet in the ArrayList<E> is a good example.

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

private class Itr implements Iterator<E> {

Anonymous Classes

The life cycle of a method and its local variables is the same.
The life cycle of the inner class is longer than the method.
For the above reasons,
Anonymous Classes defined in the methods is restricted to access only the final local variable.