题
public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
有人可以告诉我如何打印消息 bMethod
?
解决方案
你只能实例化 MethodLocalInner
之内 aMethod
. 。也如此
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
foo.bMethod();
}
其他提示
方法内 一个方法 类声明之后 方法局部内部 例如,您可以执行以下调用:
new MethodLocalInner().bMethod();
你为什么不直接创建一个实例 MethodLocalInner
, , 在 aMethod
, ,并致电 bMethod
在新实例上?
这可能会让你开始,(我没有任何方便的测试工具)。请注意修改后的构造函数语法:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
您需要在 main 方法中调用 new Outer().aMethod() 。您还需要在 aMethod() 中添加对 MethodLocalInner().bMethod() 的引用,如下所示:
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();
}
不隶属于 StackOverflow