Search code examples
javainner-classesmethod-invocation

Method Local Inner Class


public class Test {
    public static void main(String[] args) {

    }
}

class Outer {
    void aMethod() {
        class MethodLocalInner {
            void bMethod() {
                System.out.println("Inside method-local bMethod");
            }
        }
    }
}

Can someone tell me how to print the message from bMethod?


Solution

  • You can only instantiate MethodLocalInner within aMethod. So do

    void aMethod() {
    
        class MethodLocalInner {
    
                void bMethod() {
    
                        System.out.println("Inside method-local bMethod");
                }
        }
    
        MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
        foo.bMethod();
    
    }