Method Local Inner Classes in Java

We can declare a Class inside method such type of Inner Classes are known as method local Inner Classes.

The method’s local inner class’s main objective is to define a method-specific repeatedly required functionality. Method local inner classes are best suitable to meet nested method requirements.

We can access method local inner classes only inside a method where it is declared, we can not access from outside the method. Because of its low scope Method local innner classes are most rarely used type of Inner Classes.

class OuterClass {
    public void method(){
        class Inner{
            public void Addition(int num1, int num2){
                System.out.println("The Addition Result =" + (num1 + num2) );
            }
        }
        Inner obj = new Inner();
        obj.Addition(10,100);
        obj.Addition(20,200);
    }

    public static void main(String[] args) {
        OuterClass obj = new OuterClass();
        obj.method();
    }
    }
Method Local Inner Classes in Java

  • Inside Instance and static method we can declare the method local inner class.
class OuterClass {
    int num = 99;
    static int num2 =999;
    private void method(){
        class Inner{
            public void method1(){
                System.out.println(num);
                System.out.println(num2);
            }
        }
        Inner obj = new Inner();
        obj.method1();
    }

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

  • If we declare an Inner Class inside the instance method directly then from that method’s local inner class we can access both static and nonstatic members of the outer class directly.
  • If we declare an inner class inside a static method then from that method’s local inner class we can only access static members of the outer class directly.

Similar Java Tutorials

Leave a Comment