Inner Class in Java – GeeksforGeeks

In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? 

There are certain advantages associated with inner classes are as follows:

  • Making code clean and readable.
  • Private methods of the outer class can be accessed, so bringing a new dimension and making it closer to the real world.
  • Optimizing the code module.

We do use them often as we go advance in java object-oriented programming where we want certain operations to be performed, granting access to limited classes and many more which will be clear as we do discuss and implement all types of inner classes in Java.

Types of Inner Classes

There are basically four types of inner classes in java.

  1. Nested Inner Class
  2. Method Local Inner Classes
  3. Static Nested Classes
  4. Anonymous Inner Classes

Let us discuss each of the above following types sequentially in-depth alongside a clean java program which is very crucial at every step as it becomes quite tricky as we adhere forwards.

Type 1: Nested Inner Class 

It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers. 

Example 1A

Java




 

class Outer {

 

    

    

    class Inner {

 

        

        public void show()

        {

 

            

            System.out.println("In a nested class method");

        }

    }

}

 

class Main {

 

    

    public static void main(String[] args)

    {

 

        

        

        Outer.Inner in = new Outer().new Inner();

 

        

        in.show();

    }

}



Output

In a nested class method

Note:  We can not have a static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself. For example, the following program doesn’t compile. 

Example 1B

Java




 

class Outer {

 

    

    void outerMethod()

    {

 

        

        System.out.println("inside outerMethod");

    }

 

    

    

    class Inner {

 

        

        public static void main(String[] args)

        {

 

            

            System.out.println("inside inner class Method");

        }

    }

}



Output:

An interface can also be nested and nested interfaces have some interesting properties. We will be covering nested interfaces in the next post.

Type 2: Method Local Inner Classes 

Inner class can be declared within a method of an outer class which we will be illustrating in the below example where Inner is an inner class in outerMethod().

Example 1

Java




 

class Outer {

 

    

    void outerMethod()

    {

 

        

        System.out.println("inside outerMethod");

 

        

        

        

        class Inner {

 

            

            void innerMethod()

            {

 

                

                

                System.out.println("inside innerMethod");

            }

        }

 

        

        Inner y = new Inner();

 

        

        y.innerMethod();

    }

}

 

class GFG {

 

    

    public static void main(String[] args)

    {

 

        

        

        Outer x = new Outer();

 

        

        

        x.outerMethod();

    }

}



Output

inside outerMethod
inside innerMethod

Method Local inner classes can’t use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error. 

Note: “x” is not final in outerMethod() and innerMethod() tries to access it.

Example 2

Java




class Outer {

   void outerMethod() {

      int x = 98;

      System.out.println("inside outerMethod");

      class Inner {

         void innerMethod() {

            System.out.println("x= "+x);

         }

      }

      Inner y = new Inner();

      y.innerMethod();

   }

}

class MethodLocalVariableDemo {

   public static void main(String[] args) {

      Outer x=new Outer();

      x.outerMethod();

   }

}



Output

inside outerMethod
x= 98

Note: Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in method local inner class. 

But the following code compiles and runs fine (Note that x is final this time) 

Example 3

Java




class Outer {

   void outerMethod() {

      final int x=98;

      System.out.println("inside outerMethod");

      class Inner {

         void innerMethod() {

            System.out.println("x = "+x);

         }

      }

      Inner y = new Inner();

      y.innerMethod();

   }

}

class MethodLocalVariableDemo {

    public static void main(String[] args){

      Outer x = new Outer();

      x.outerMethod();

    }

}



Output

inside outerMethod
x = 98

The main reason we need to declare a local variable as a final is that the local variable lives on the stack till the method is on the stack but there might be a case the object of the inner class still lives on the heap. 
Method local inner class can’t be marked as private, protected, static, and transient but can be marked as abstract and final, but not both at the same time.

Type 3: Static Nested Classes

Static nested classes are not technically inner classes. They are like a static member of outer class. 

Example

Java




 

import java.util.*;

 

class Outer {

 

    

    private static void outerMethod()

    {

 

        

        System.out.println("inside outerMethod");

    }

 

    

    

    static class Inner {

 

        public static void display()

        {

 

            

            System.out.println("inside inner class Method");

 

            

            outerMethod();

        }

    }

}

 

class GFG {

 

    

    public static void main(String args[])

    {

 

        Outer.Inner obj = new Outer.Inner();

 

        

        obj.display();

    }

}



Output

inside inner class Method
inside outerMethod

Type 4: Anonymous Inner Classes 

Anonymous inner classes are declared without any name at all. They are created in two ways. 

  • As a subclass of the specified type
  • As an implementer of the specified interface

Way 1: As a subclass of the specified type 

Example:

Java




 

import java.util.*;

 

class Demo {

 

    

    void show()

    {

        

        System.out.println(

            "i am in show method of super class");

    }

}

 

class Flavor1Demo {

 

    

    static Demo d = new Demo() {

        

        

        void show()

        {

            

            

            super.show();

 

            

            System.out.println("i am in Flavor1Demo class");

        }

    };

 

    

    

    public static void main(String[] args)

    {

        

        d.show();

    }

}



Output

i am in show method of super class
i am in Flavor1Demo class

In the above code, we have two classes Demo and Flavor1Demo. Here demo act as a super-class and the anonymous class acts as a subclass, both classes have a method show(). In anonymous class show() method is overridden.

Way 2: As an implementer of the specified interface  

Example:

Java




 

interface Hello {

 

    

    void show();

}

 

class GFG {

 

    

    static Hello h = new Hello() {

       

        

        

        public void show()

        {

            

            System.out.println("i am in anonymous class");

        }

    };

 

    

    

    public static void main(String[] args)

    {

        

        h.show();

    }

}



Output

i am in anonymous class

Output explanation:

In the above code, we create an object of anonymous inner class but this anonymous inner class is an implementer of the interface Hello. Any anonymous inner class can implement only one interface at one time. It can either extend a class or implement an interface at a time.
This article is contributed by Pawan Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes

arrow_drop_up