简体   繁体   中英

Outer and Inner class and static methods

I understand that an Inner Class it's non-static and a static method from the Outer Class can't reference it.

I have this code, that doesn't work, and I understand why that doesn't work.

class OuterClass {
    class InnerClass{}
    public static void outherMethod() {
        InnerClass i = new InnerClass();
    }
}

But then I have this other code, that DOES work, but I don't understand why it's different from the first one. Why does it work?

class OuterClass {
    class InnerClass{}
    public static void outherMethod() {
        InnerClass i = new OuterClass.new InnerClass();
    }
}

Thanks in advance!

EDIT: it's not duplicated because it isn't the same question. I'm not asking about static nested classes, I'm asking about static methods and inner classes

An inner class always requires an instance of the enclosing class in order to be instantiated.

A static method of OuterClass doesn't have an instance of OuterClass , so you can't create an instance of InnerClass without supplying an enclosing instance (of OuterClass ).

InnerClass i = new InnerClass();

would work only from within an instance method of OuterClass .

InnerClass i = new OuterClass().new InnerClass();

works from within a static method since you are creating an instance of OuterClass and use it as the enclosing instance for an instance of InnerClass .

The key point to note here is Inner class is a member of Outer class.

So without an instance of it, you can't access it's members.

From docs directly

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

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