Inner class means one class that is a member of another class. There are basically four types of inner classes in java.
- Nested Inner class
- Method Local inner classes
- Anonymous inner classes
- 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 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 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