Method Local Inner Class

核能气质少年 提交于 2019-12-10 23:58:59

问题


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?


回答1:


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

}



回答2:


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

new MethodLocalInner().bMethod();



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/80592/method-local-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!