Skip to content
Related Articles

Related Articles

Improve Article
Java Program to illustrates Use of Static Inner Class
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2020

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :