Method local inner classes

Method local inner classes 
  • Sometimes we can declare a class inside a method such type of inner classes are called method local inner classes.
  • The main objective of method local inner class is to define method specific repeatedly required functionality.
  • Method Local inner classes are best suitable to meet nested method requirement.
  • We can access method local inner class only within the method where we declared it. That is from outside of the method we can’t access. As the scope of method local inner classes is very less, this type of inner classes are most rarely used type of inner classes.
package com.ashok.innerclasses;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class OuterClass {
   public void method() {
      class InnerClass {
         public void sum(int a, int b) {
            System.out.println("The sum is : " + (a + b));
         }
      }
      InnerClass i = new InnerClass();
      i.sum(5, 10);
      i.sum(50, 200);
   }

   public static void main(String[] args) {
      new OuterClass().method();
   }
}

Output

The sum is : 15
The sum is : 250
  • If we are declaring inner class inside instance method then we can access both static and non static members of outer class directly.
  • But if we are declaring inner class inside static method then we can access only static members of outer class directly and we can’t access instance members directly.
package com.ashok.innerclasses;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class OuterClass {
   String str = "Waytoeasylearn";
   static int i = 100;

   public void methodOne() {
      class InnerClass {
         public void methodTwo() {
            System.out.println(str);
            System.out.println(i);
         }
      }
      InnerClass in = new InnerClass();
      in.methodTwo();
   }

   public static void main(String[] args) {
      new OuterClass().methodOne();
   }
}

Output

Waytoeasylearn
100
  • If we declare methodOne() method as static then we will get compile time error saying “non-static variable x cannot be referenced from a static context”.
  • From method local inner class we can’t access local variables of the method in which we declared it. But if that local variable is declared as final then we won’t get any compile time error.
Method local inner classes

Scroll to top