根据Java Tutorial,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法,但它只能通过对象引用来使用它们。有人能举个例子吗?我是否需要在静态嵌套类中创建封闭类的实例,然后引用实例的实例变量/方法?
答案 0 :(得分:0)
考虑一个名为Main
且带有private
字段value
的类,给定一个名为static
的{{1}}嵌套类,如果没有Nested
,则无法访问value
Main
的一个实例。喜欢,
public class Main {
private final int value = 100;
static class Nested {
static void say(Main m) {
System.out.println(m.value); // <-- without m, this is illegal.
}
}
}
请注意,value
private
但Nested
可以访问它(通过参考 m
)。
答案 1 :(得分:0)
class A {
public void foo() {...}
public static class B {
public void bar() {
foo(); // you can't do this, because B does not have a containing A.
//If B were not static, it would be fine
}
}
}
// somewhere else
A.B val = new A.B(); // you can't do this if B is not static