简体   繁体   中英

How to instantiate multiple nested non-static inner classes - java

I have the following piece of code:

public class InnerClassStuff {
   public class A{
       public class AA{}
    }
}

my question is how can I instantitae an AA object?

I've tried the following but it won't compile:

public static void main(String[] args){
   InnerClassStuff object = new InnerClassStuff();
   A a = object.new A();
   AA aa = object.a.new AA(); //error
}

To instantiate an inner class, you must first instantiate the outer class. So, you can't declare A a= .. , you need wrapped it with outer class like below:

InnerClassStuff object = new InnerClassStuff();
InnerClassStuff.A.AA a = object.new A().new AA();

Or,

InnerClassStuff object = new InnerClassStuff();
InnerClassStuff.A a = object.new A();
InnerClassStuff.A.AA aa = a.new AA();

To access the class you have to use The outer class name, only by doing so you can have reference variable of inner class. eg:

InnerClassStuff object = new InnerClassStuff();
InnerClassStuff.A a = object.new A();
InnerClassStuff.A.AA aa = a.new AA();

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