Java Inner classes

java

In Java, an inner class is a class defined within another class. Inner classes have access to all the variables and methods of the outer class and can be used to group related functionality or to implement helper classes.

There are four types of inner classes in Java:

  • Non-static inner classes (also called inner classes) have an enclosing instance and can access all the variables and methods of the outer class.
  • Static inner classes (also called nested classes) do not have an enclosing instance and can only access the static variables and methods of the outer class.
  • Local classes are defined within a block of code and can only be used within that block. They have the same scope as local variables.
  • Anonymous classes are inner classes without a name. They are often used to create objects of a specific type on the fly.

Here is an example of an inner class in Java:

public class OuterClass {
  private int x = 10;

  public class InnerClass {
    public void printX() {
      System.out.println(x);
    }
  }
}

To create an instance of the inner class, you must first create an instance of the outer class:

OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.printX(); // prints 10