2
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?

4 Answers 4

6

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();

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..realised where I went wrong..I put the new instance line before the localinner class creation.
1

Within the method aMethod after the declaration of the class MethodLocalInner you could for instance do the following call:

new MethodLocalInner().bMethod();

Comments

1

Why don't you just create an instance of MethodLocalInner, in aMethod, and call bMethod on the new instance?

Comments

0

You need to call new Outer().aMethod() inside your main method. You also need to add a reference to MethodLocalInner().bMethod() inside your aMethod(), like this:

public class Test {
    public static void main(String[] args) {
        new Outer().aMethod();
    }
}


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.