简体   繁体   中英

Instantiating non-static inner class from a static method

I arrived at a situation as described by this question.
Got the solution.
But!! Still can't understand why can't you instantiate a non-static inner class from a static method, but you can, if the non-static class is written in a separate file (ie not as an inner class)

Inner classes have special characteristics. One of them being the following taken from the Oracle Java Tutorials .

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.

Static nested classes and classes in their own java files do not have the dependency on an outer object like inner classes do so you can create a new one without requiring an instance of the enclosing class.

Because an instance of a non-static inner class holds a reference to it's owner object (the instance of the outer class that created it). A static method does not have an associated outer object so it canot create an inner because there is no outer to give it.

class Outer {
    Object somethingInTheOuterObject;

    class Inner {
        // Secretly holds a reference to its outer.

        void f() {
            // Can access my enclosing instance objects.
            Object o = somethingInTheOuterObject;
        }
    }
}

static void f() {
    // Cannot do this.
    new Outer.Inner();
    // Can do this.
    Outer outer = new Outer();
    // Can do this.
    Outer.Inner inner = outer.new Inner();
    // Can even do this.
    Outer.Inner inner1 = new Outer().new Inner();
}

It's the same as instanciate Integer or any other class in a static method. The scope is local, so it's permitted.

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