Omnipotent
Omnipotent

Reputation: 28207

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?

Upvotes: 2

Views: 4702

Answers (4)

Fco Javier Perez
Fco Javier Perez

Reputation: 1

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

Upvotes: 0

Val
Val

Reputation:

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

}

Upvotes: 6

Lior
Lior

Reputation: 179

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

Upvotes: 1

Benno Richters
Benno Richters

Reputation: 15673

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

new MethodLocalInner().bMethod();

Upvotes: 1

Related Questions