简体   繁体   中英

Order of local inner class

Why local inner classes depends on order of definition. For example local inner class which is defined first cannot create object to the classes defined right after the first local inner class.

`package inner;

public class OuterClass {
    class Inner1{
        Inner2 ic=new Inner2(); // No compilation error 

    }
    class Inner2 {
        Inner1 in=new Inner1();
    }

    public static void main(String[] args) {
        class A2{
            A1 a=new A1(); // Compilation error
        }
        class A1{
            int a1;
            A2 a=new A2();
        }
    }
}
`

This is because A2 and A1 are local classes, and according to The Java Language Specification , section 6.3 Scope of a Declaration:

The scope of a local class declaration immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration.

As the scope is the rest of the immediately enclosing block, you cannot use the local class before its declaration.

Inner classes are associated with an instance of its enclosing class and have access to other members of the enclosing class.

An inner class is a member of its enclosing class and objects that are instances of an inner class exist within an instance of the outer class.

You can take a look at Nested Classes tutorial

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