How to call a method from a nested class, Java?

旧街凉风 提交于 2019-12-22 11:29:05

问题


How to call methodTwo(); from methodOne(); ?

class Name {
    void methodOne() {
        class InnerClass {
           void methodTwo() {
           }
         }
     }
 }

Thank You!


回答1:


You need to create an instance of the InnerClass, in the same way as any other instance method needs an instance on which to call it:

class Name {
   void methodOne() {
     class InnerClass {
       void methodTwo() {
       }
     }

     InnerClass x = new InnerClass();
     x.methodTwo();
   }
}

It's worth being careful before doing this - I don't think I've ever seen a named class declared within a method in the production code I've been associated with. Normally I'd either use an anonymous inner class for something really short, or a private static named class for anything longer, to avoid making the method too long.




回答2:


class Name {
    void methodOne() {
        class InnerClass {
           void methodTwo() {
               new InnerClass().methodTwo();
           }
        }
    }
}



回答3:


Non-static nested classes are tied with containing class, but it can be many instances of nested class with one containing instance. So you need to specify instance name against which you want to run a method.



来源:https://stackoverflow.com/questions/11361616/how-to-call-a-method-from-a-nested-class-java

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