简体   繁体   English

如何在java中实例化成员类的数组

[英]How to instantiate an array of a member class in java

I have a class called MultiplePrintableInvoiceData, and this class has an inner class which is a member class called Product. 我有一个名为MultiplePrintableInvoiceData的类,这个类有一个内部类,它是一个名为Product的成员类。

I can instantiate an instance of Product in another class with the following code: 我可以使用以下代码在另一个类中实例化Product实例:

MultiplePrintableInvoiceData pid = new MultiplePrintableInvoiceData();
MultiplePrintableInvoiceData.Product product = pid.new Product();

but when I try to instantiate an array of Product with the following code: 但是当我尝试使用以下代码实例化Product数组时:

MultiplePrintableInvoiceData.Product[] product = pid.new Product[];

I get a compilation error: "(" expected - illegal start of expression. Please I need help. 我收到编译错误:“(”预期 - 表达非法开始。请我帮忙。

Update I have modified the code to: 更新我已将代码修改为:

MultiplePrintableInvoiceData.Product[] product = pid.new Product[11];

But it is still giving me an error! 但它仍然给我一个错误!

It's not possible to create an object of the inner class unless we already have an object of the outer class. 除非我们已经拥有外部类的对象,否则无法创建内部类的对象。 This is because the object of the inner class is quietly connected to the object of the outer class that it was made from. 这是因为内部类的对象安静地连接到它所构成的外部类的对象。 However, if you make a nested class (a static inner class), then it doesn't need a reference to the outer-class object. 但是,如果创建嵌套类( 静态内部类),则不需要对外部类对象的引用。

However, This is not the case while creating an array of inner class. 但是,创建内部类的数组时不是这种情况。 We can't use Object of outer class for referencing to inner class while creating Array of inner class. 在创建内部类的Array的同时,我们不能使用外部类的Object来引用内部类。 because, we are not creating any inner objects. 因为,我们没有创造任何内在的对象。 We are only creating an array, which is just a place to put inner objects. 我们只创建一个数组,它只是放置内部对象的地方。 It does not need to belong to any outer objects. 它不需要属于任何外部对象。

  class Outer
  {
      class Inner
      {
        // field declaration and other code
      }
  }
  //...........
  Outer outerObj = new Outer();
  Outer.Inner innerObj = outerObj.new Inner(); // instance creation of inner class

  Outer.Inner[] innrArr = new Outer.Inner[5]; // array creation of inner class

For your context, You need to do: 对于您的上下文,您需要:

MultiplePrintableInvoiceData.Product[] product = new MultiplePrintableInvoiceData.Product[10];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM