Bootstrap
本文主要介绍Java中静态内部类(inner class)调用其外部类(outer class)的的非静态方法问题,以及解决方法和示例代码。

1、直接调用外部类非静态方法报错

public class OuterClass {
public void printMessage(String message) {
System.out.println(message);
}
private static class InnerClass {
public void sayHello() {
printMessage("Hello world!"); //error: Cannot make a static reference to the non-static method printMessage(String)
}
}
}

2、通过实例来调用外部类非静态方法

由于InnerClass是static,需要通过其它方式获取实例引用,常用的方式就是通过参数,例如:

public class OuterClass {
private void printMessage(String message) {
System.out.println(message);
}
private static class InnerClass {
private void sayHello(OuterClass outer) {
outer.printMessage("Hello world!"); // allowed
}
}
}

另外,如果InnerClass没有嵌套在里面OuterClass,它将无法访问该private方法,例如:

public class OuterClass {
private void printMessage(String message) {
System.out.println(message);
}
}
class InnerClass {
private void sayHello(OuterClass outer) {
outer.printMessage("Hello world!"); // ERROR: The method printMessage(String) from the type OuterClass is not visible
}
}