0

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
}

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Or replace the last line of the original code with AA aa = a.new AA();
I tried using AA aa = a.new AA(); but it gave me an error saying "AA cannot be resolved to a type". I am using eclipse by the way.
@JerryJia, You can't directly use Inner class. You should wrapped it with outer class.
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.