Gangmax Blog

自由之思想,独立之精神

The Difference Between Java Inner Class and Static Nested Class

| Comments

From here.

Two differences:

  1. The inner class instance can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance, while the static nested class can exist without an instance of OuterClass and has no direct access to the methods and fields of its enclosing instance.

  2. The inner class instance is initialized by “parentClassInstance.new InnerClass()”, while the static nested class instance is intialized by “new ParentClass.StaticNestedClass()”.

Test.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Test {
    private String name;

    public Test(String name) {
        this.name = name;
    }

    public class InnerTest {
        public void say() {
            System.out.println("Hello " + name);
        }
    }

    public static void main(String[] args) {
        Test t = new Test("Max");
        InnerTest it = t.new InnerTest();
        it.say();
    }
}
Test2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Test2 {
    private String name;

    public Test2(String name) {
        this.name = name;
    }

    public static class InnerTest {
        public void say() {
            // For a static nested class, it cannot access the outer
            // parent instance variable.
            System.out.println("Hello!");
        }
    }

    public static void main(String[] args) {
        Test2 t = new Test2("Max");
        // For a static nested class, new it with "ParentClass.NestedStaticClass"
        // directly instead of "parentClassInstance.new NestedStaticClass()".
        InnerTest it = new Test2.InnerTest();
        it.say();
    }
}

Comments