1

Consider the following nested classes.

class Outerclass {

    class innerclass {

    }

}

 class util {

 //how to declare an array of innerclass objects here?
}
Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689
Namratha
  • 16,400
  • 26
  • 87
  • 124

2 Answers2

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();
}
Rahul
  • 43,125
  • 11
  • 82
  • 101
  • 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? – Namratha Jan 23 '14 at 05:59
  • 1
    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. – Rahul Jan 23 '14 at 06:09
  • 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. – Namratha Jan 23 '14 at 06:30
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;
akim
  • 7,642
  • 2
  • 41
  • 56
Jagadesh Seeram
  • 3,019
  • 1
  • 14
  • 29