简体   繁体   中英

Static nested classes in Java

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.

You aren't accessing instance members directly.

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM