1

Consider the following nested classes.

class Outerclass {

    class innerclass {

    }

}

 class util {

 //how to declare an array of innerclass objects here?
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Namratha
  • 16,630
  • 27
  • 90
  • 125

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
  • 44,383
  • 11
  • 84
  • 103
  • 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
  • 8,255
  • 3
  • 44
  • 60
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29