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?
Asked
Active
Viewed 922 times
2 Answers
2
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
).

Elliott Frisch
- 198,278
- 20
- 158
- 249
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

ControlAltDel
- 33,923
- 10
- 53
- 80
-
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. – John Strood Jan 11 '22 at 16:46