Nested Inner Class in Java


A class is a non-primitive or user-defined data type in Java, while an object is an instance of a class. To define a class within another class. Such a class is called a Nested Class. Nested Classes are called Inner Classes if they were declared as non-static, if not, they are simply called Static Nested Classes. This page is to document and provide details with examples on how to use Java Nested and Inner Classes.

Syntax:
   class Class_Name   // OuterClass
   {
    . . .
      class Class_Name  // NestedClass
      {
       . . .
      }
   }

This program demonstrates nested classes in Java. There are two classes defined: outer and inner. inner is defined inside outer. outer has an integer variable a and a method outerDisplay().

The outerDisplay() method creates an instance of inner and calls its innerDisplay() method. The method also prints the value of b from the inner class.

inner has an integer variable b and a method innerDisplay(). The innerDisplay() method prints the values of a and b from the outer and inner classes, respectively.

The main() method creates an instance of outer and calls its outerDisplay() method. It also creates an instance of inner and calls its innerDisplay() method. Since inner is a nested class, it can only be accessed through an instance of outer.

Source Code

// Nested Inner Class
class outer {
    int a=50;
    class inner
    {
        int b=58;
        void innerDisplay()
        {
            System.out.println("A : "+a);
            System.out.println("B : "+b);
        }
 
    }
    void outerDisplay()
    {
        inner i =new inner();
        i.innerDisplay();
        System.out.println("B from inner Class by Outer Display : "+i.b);
    }
}
    public class nestedClass {
    public static void main(String args[]) {
        outer o =new outer();
        o. outerDisplay();
        outer.inner i =new outer().new inner();
        i.innerDisplay();
    }
}

Output

A : 50
B : 58
B from inner Class by Outer Display : 58
A : 50
B : 58
To download raw file Click Here

Basic Programs