Friday, September 26, 2025
HomeLanguagesJavaJava Program to illustrates Use of Static Inner Class

Java Program to illustrates Use of Static Inner Class

Inner class means one class that is a member of another class. There are basically four types of inner classes in java.

  1. Nested Inner class
  2. Method Local inner classes
  3. Anonymous inner classes
  4. Static nested classes

Java also allows a class to be defined within another class. These are called Nested Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes. In this article, we will implement a static inner class in java programs.

Example 1: An Instance of the static inner class is created and its method is called later.

Java




// Java Program to Illustrates Use of Static Inner Class
  
// Outer class
public class Gfg {
  
    // Display message of inner class
    static String msg = "GeeksForGeeks";
  
    // Static Inner Class
    static class InnerClass {
  
        // Static Inner Class Method
        public void display()
        {
            // Display message of inner class
            System.out.println("Welcome to " + msg);
        }
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of the static inner class
        InnerClass instance = new InnerClass();
  
        // Calling method display through
        // the inner class instance variable
        instance.display();
    }
}


Output:

Welcome to GeeksForGeeks

Example 2: Creating an instance of the outer class and calling the static inner class method.

Java




// Java Program to Illustrates Use of Static Inner Class
  
// Outer class
public class GFG {
  
    // Static string message
    static String msg = "GeeksForGeeks";
  
    // Static Inner Class
    static class InnerClass {
  
        // Static Inner Class Method
        public void display()
        {
            // Display message in inner class
            System.out.println("Welcome to " + msg);
        }
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of the outer class
        Gfg.InnerClass instance = new Gfg.InnerClass();
  
        // Calling method of static inner class through
        // the outer class instance variable
        instance.display();
    }
}


Output:

Welcome to GeeksForGeeks
RELATED ARTICLES

Most Popular

Dominic
32320 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6683 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6795 POSTS0 COMMENTS
Ted Musemwa
7071 POSTS0 COMMENTS
Thapelo Manthata
6756 POSTS0 COMMENTS
Umr Jansen
6762 POSTS0 COMMENTS