Static Inner Class in Java


The static keyword is used on a class, method, or field to make them work independently of any instance of the class.Static fields are common to all instances of a class. They do not need an instance to access them.

Here, the OuterClass defines a static variable x and an instance variable y. The InnerClass is a static inner class of OuterClass. It defines a method display() that prints the value of x. Since it is a static inner class, it can be accessed without creating an instance of OuterClass.

In the main method, an instance of the InnerClass is created using the syntax OuterClass.InnerClass i = new OuterClass.InnerClass(). The display() method of InnerClass is then called using this instance i, which prints the value of x.

Source Code

//Static Inner Class
class OuterClass {
    static int x=10;
    int y=20;
    static class InnerClass
    {
        void display()
        {
            System.out.println("X : "+x);
        }
    }
}
 
public class staticInnerClass {
    public static void main(String[] args) {
        OuterClass.InnerClass i =new OuterClass.InnerClass();
        i.display();
    }
}
 

Output

X : 10
To download raw file Click Here

Basic Programs