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
      {
       . . .
      }
   }

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