According to the Java Tutorial, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, BUT it can use them only through an object reference. Can someone give me an example? Would I need to create an instance of the enclosing class in the static nested class and then reference the instance's instance variables/methods?
2 Answers
Consider a class named Main with a private field value, given a static nested class named Nested you cannot access value without an instance of Main. Like,
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.
}
}
}
Note that value is private but Nested can access it (through a reference m).
Comments
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
1 Comment
John Strood
I know you can't do this but shouldn't this work?
A a = new A(); A.B b = new a.B(); Other static members can be accessed this way.