Wednesday, 1 October 2025

Inner Classes in Java

A class can be defined inside another class. Such classes are called nested classes.

The nested class is like a member of the enclosing class. The enclosing class cannot access the members of the nested class directly. But the nested class can access all the members of the enclosing class, including the private members. 

For example,  


In the above figure, class B is nested inside class A. Class B is a member of Class A and can access all its members directly. But class A cannot access the members of class B.

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

Static nested class

The static nested class is declared with a static modifier. It can access only the static members of the enclosing class. It does not have access to the non-static members of the outer class.

class Outer 
{
    static class Inner 
    {
        public static void display() 
        {
            System.out.println("inside inner class Method");
        }
    }
}
public class Main 
{
    public static void main(String[] args) 
    {
        Outer.Inner.display();
    }
}

Non-static nested class / Inner class

An inner class is a non-static nested class. It can access all the variables and methods of the outer class, including the private members, directly. Members of the inner class are known only within the scope of the inner class and may not be used by the outer class.

// Demonstrate an inner class. 
class Outer 
  int outer_x = 100; 
  void test() 
  { 
    Inner inner = new Inner(); 
    inner.display(); 
  } 
  // this is an inner class 
   class Inner 
   { 
        void display() 
        { 
                    System.out.println("display: outer_x = " + outer_x); 
        } 
    } 
class InnerClassDemo 
  public static void main(String[] args) 
  { 
    Outer outer = new Outer(); 
    outer.test(); 
  } 
}
 
Advantages of Inner Class

Encapsulation: Inner classes can access private members of the outer class, improving encapsulation.

Code Organisation: They group related logic, making the code more modular and easier to maintain.

Polymorphism: Inner classes can implement polymorphic behavior by extending or implementing different classes/interfaces.

Callbacks: Useful for event-driven programming, such as defining callback functions.

Inner classes are a powerful feature in Java, enabling better design and modularity in object-oriented programming.