What are method local inner classes in Java?


In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted to the method.

A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class.

Example

Live Demo

public class OuterClass {
   public void display(){
      int num = 23;
      class Inner{
         public void print() {
            System.out.println("This is method inner class "+num);
         }
      }
      Inner obj = new Inner();
      obj.print();
   }
   public static void main(String args[]){
      OuterClass outer = new OuterClass();
      outer.display();
   }
}

Output

This is method inner class 23

Updated on: 16-Jun-2020

903 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements