Java Inner/Nested Classes

The Java programming language allows you to define a class within another class or interface. Such a class is called a nested class and is illustrated here:

class OuterClass {

    ...

    class NestedClass {

        ...

    }

}

The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes.

The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

Compelling reasons for using nested classes include the following:

It is a way of logically grouping classes that are only used in one place: 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. Nesting such “helper classes” makes their package more streamlined.

It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. 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.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

OuterClass outerObject = new OuterClass();

OuterClass.InnerClass innerObject = outerObject . new InnerClass();

class OuterClass {

  int x = 10;

  class InnerClass {

    int y = 5;

  }

}

public class Main {

  public static void main(String[] args) {

    OuterClass myOuter = new OuterClass();

    OuterClass.InnerClass myInner = myOuter.new InnerClass();

    System.out.println(myInner.y + myOuter.x);

  }

}

// Outputs 15 (5 + 10)

There are two types of nested classes non-static and static nested classes.

The non-static nested classes are also known as inner classes.

  • Non-static nested class (inner class)
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class
  • Static nested class

A static class in Java is a class that is created inside a class, is called static nested class.

It cannot access non-static data members/attributes and methods. It can be accessed by outer class name.

An inner class can also be static, which means that you can access it without creating an object of the outer class: