3

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.

Oliver Charlesworth
274k34 gold badges591 silver badges688 bronze badges
asked Jan 16, 2013 at 2:15

3 Answers 3

8

You aren't accessing instance members directly.

staticMember is accessing a non-instance member, and nested.member is accessing one through an object reference.

answered Jan 16, 2013 at 2:17
Sign up to request clarification or add additional context in comments.

2 Comments

What I'm curious about was that I can access nested.member without an accessor method...inner classes can access directly private members of the outer class I suppose...
@cjtightpant: Yes, that's true.
2

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);
answered Jan 16, 2013 at 2:22

Comments

1

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

answered Jan 16, 2013 at 2:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.