1

Consider the following nested classes.

class Outerclass {

    class innerclass {

    }

}

 class util {

 //how to declare an array of innerclass objects here?
}
1

2 Answers 2

13

You can declare an array of innerclass objects like this.

class util {
    Outerclass.innerclass[] inner = new Outerclass.innerclass[10];
}

And to instantiate them you can do something like this inside the util class.

void test() {
    Outerclass outer = new Outerclass();
    inner[0] = outer.new innerclass();
}
Sign up to request clarification or add additional context in comments.

3 Comments

when you say myclass[] a = new myclass[5]; we don't intialize again right? So, when we say new Outerclass.innerclass[10]; isn't that enough to allocate memory for the array? Why do we have to do Outerclass outer = new Outerclass(); inner[0] = outer.new innerclass(); again?
You've created an array of innerclass. Won't you have to initialize each element in the array? If it was a primitive data type like int, all the elements would be filled with 0 by default. But in this case, it'd be null. All the array elements needs to be initialized. You've just declared and initialized the an array, but have not initialized the elements in the array.
won't new Outerclass.innerclass[10]; call the constructors of both the outer and inner classes? If the constructor of the inner class is called then we wouldn't have to initialize it by ourselves.
2
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerArray[] = new OuterClass.InnerClass[3];
// Creating Objects of Inner Class
OuterClass.InnerClass innerObject1 = outerObject.new InnerClass();
OuterClass.InnerClass innerObject2 = outerObject.new InnerClass();
OuterClass.InnerClass innerObject3 = outerObject.new InnerClass();
// Adding the Objects to the Array
innerArray[0] = innerObject1;
innerArray[1] = innerObject2;
innerArray[2] = innerObject3;

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.