完全可以。如果不是静态内部类,那没有什么限制!
如果你把静态嵌套类当作内部类的一种特例,那在这种情况下不可以访问外部类的普通成员变量,而只能访问外部类中的静态成员
举例:
class OuterMyTest {
static int i = 1;
int j = 2;
class Test {
void getFun() {
System.out.println(i);
System.out.println(j);
}
}
public static void main(String[] args) {
OuterMyTest outerMyTest = new OuterMyTest();
Test interTest = outerMyTest.new Test();
interTest.getFun();
}
}
运行结果:1 2
class OuterMyTest {
static int i = 1;
int j = 2;
static class Test {
void getFun() {
System.out.println(i);
System.out.println(j); //编译报错,静态内部类只能访问静态成员
}
}
public static void main(String[] args) {
Test interTest = new Test();
interTest.getFun();
}
}
编译报错:Cannot make a static reference to the non-static field
静态内部类只能访问静态成员!!!!