静态嵌套类通过对象引用访问实例变量的Java示例
根据Java教程,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法,但只能通过对象引用使用它们。有人能给我举个例子吗?我是否需要在静态嵌套类中创建封闭类的实例,然后引用该实例的实例变量/方法?考虑一个名为Main的类,该类有一个私有字段值,给定一个名为nested的静态嵌套类,如果没有Main实例,则无法访问该值。像 请注意,该值是私有的,但嵌套的可以通过引用m访问它静态嵌套类通过对象引用访问实例变量的Java示例,java,static,inner-classes,Java,Static,Inner Classes,根据Java教程,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法,但只能通过对象引用使用它们。有人能给我举个例子吗?我是否需要在静态嵌套类中创建封闭类的实例,然后引用该实例的实例变量/方法?考虑一个名为Main的类,该类有一个私有字段值,给定一个名为nested的静态嵌套类,如果没有Main实例,则无法访问该值。像 请注意,该值是私有的,但嵌套的可以通过引用m访问它 public class Main { private final int value = 100; st
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.
}
}
}
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