I'm unsure why this code compiles... quoting the Java tutorials:
like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Src: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
public class StaticNested {
private String member;
private static String staticMember;
static class StaticNestedClass {
private void myMethod() {
System.out.println(staticMember);
StaticNested nested = new StaticNested();
System.out.println(nested.member);
}
}
}
I didn't expect to be able to access member directly, but the code compiles fine. Am I misunderstanding the Java spec?
Sorry about the formatting, I'm struggling with my browser + post editor.
3 Answers 3
You aren't accessing instance members directly.
staticMember is accessing a non-instance member, and nested.member is accessing one through an object reference.
2 Comments
nested.member without an accessor method...inner classes can access directly private members of the outer class I suppose...It is correct behavior. What spec meant is that (in your code example) you cant access non-static member field String member directly in static nested class like
public class StaticNested {
private String member;
private static String staticMember;
static class StaticNestedClass {
private void myMethod() {
System.out.println(staticMember);
System.out.println(member);//<-here you will get compilation error
}
}
}
but because non-static fields belongs to object of class you can access it with reference to that object like in your code
StaticNested nested = new StaticNested();
System.out.println(nested.member);
Comments
You are accessing it via an instance (not statically).
This does not compile:
System.out.println(member);
Compiler message:
Cannot make a static reference to the non-static field member