如何从嵌套类Java调用方法? [英] How to call a method from a nested class, Java?
本文介绍了如何从嵌套类Java调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何调用methodTwo();来自methodOne(); ?
How to call methodTwo(); from methodOne(); ?
class Name {
void methodOne() {
class InnerClass {
void methodTwo() {
}
}
}
}
谢谢!
推荐答案
您需要创建InnerClass
的实例,就像其他任何实例方法都需要在其上调用它的实例一样:
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.
这篇关于如何从嵌套类Java调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文