在另一个类中创建内部类对象的数组

时间:2014-01-23 05:07:02

标签: java class syntax inner-classes nested-class

考虑以下嵌套类。

class Outerclass {

    class innerclass {

    }

}

 class util {

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

2 个答案:

答案 0 :(得分:10)

您可以像这样声明一个innerclass个对象数组。

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

要实例化它们,你可以在util类中执行类似的操作。

void test() {
    Outerclass outer = new Outerclass();
    inner[0] = outer.new innerclass();
}

答案 1 :(得分: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[0] = innerObject2;
innerArray[0] = innerObject3;