What are method local inner classes in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Feb-2018 06:39:11
Advertisements