Java Inner Classes

Java Inner Classes (Nested Classes)

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

To access the inner class, you must create an object of the outer class, and then create an object of the inner class.


Types of Nested Classes

There are two main types of nested classes in Java:

  1. Non-static nested classes (Inner Classes):
    • Member Inner Class
    • Anonymous Inner Class
    • Local Inner Class
  2. Static nested classes

Member Inner Class Example

A non-static inner class (or member inner class) is a class created within another class. It has access to all members (attributes and methods) of the outer class, even the private ones.

Inner Class Example

class OuterClass {
  int x = 10;

class InnerClass { public int myInnerMethod() { // Can access attributes of the outer class return x; } } }

public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.myInnerMethod()); } }


Static Nested Class

A static class created inside a class is called a static nested class. Unlike an inner class, a static nested class cannot access the non-static members of the outer class. It can be accessed without creating an object of the outer class.

Static Nested Class Example

class OuterClass {
  static int x = 10;

static class InnerClass { int y = 5; } }

public class Main { public static void main(String[] args) { // Note how we don't need an object of OuterClass OuterClass.InnerClass myInner = new OuterClass.InnerClass(); System.out.println(myInner.y + OuterClass.x); } }