Java Nested Classes and Inner Classes

Introduction

We can create a class within another class.

Such classes are known as nested classes.

The scope of a nested class is bounded by its enclosing class.

If class B is defined within class A, then B cannot exist without A.

The nested class B has access to the members, including private members, of its nested class.

The enclosing class does not have access to the members of the nested class.

We can declare a nested class that is local to a block.

There are two types of nested classes:

  • static
  • non-static

A static nested class has the static modifier applied.

The static nested class must access the non-static members of its enclosing class through an object.

It cannot refer to non-static members of its enclosing class directly.

An inner class is a non-static nested class.

It has access to all of the variables and methods of its outer class.

The following program shows how to define and use an inner class.

// Demonstrate an inner class.
class Outer {//from   w  w w.j a  v  a  2 s  . c o m
  int outer_x = 100;

  void test() {
    Inner inner = new Inner();
    inner.display();
  }

  // this is an innner class
  class Inner {
    void display() {
      System.out.println("display: outer_x = " + outer_x);
    }
  }
}

public class Main {
  public static void main(String args[]) {
    Outer outer = new Outer();
    outer.test();
  }
}

We can define inner classes within any block scope.

For example, you can define a nested class within the block defined by a method or the body of a for loop:

// Define an inner class within a for loop.
class Outer {//from  w  ww.  j a v  a 2 s .c o  m
  int outer_x = 100;

  void test() {
    for(int i=0; i<10; i++) {
      class Inner {
        void display() {
          System.out.println("display: outer_x = " + outer_x);
        }
      }
      Inner inner = new Inner();
      inner.display();
    }
  }
}

class InnerClassDemo {
  public static void main(String args[]) {
    Outer outer = new Outer();
    outer.test();
  }
}



PreviousNext

Related