【问题标题】:How to instantiate an array of a member class in java如何在java中实例化一个成员类的数组
【发布时间】:2013-11-20 22:04:49
【问题描述】:

我有一个名为 MultiplePrintableInvoiceData 的类,这个类有一个内部类,它是一个名为 Product 的成员类。

我可以使用以下代码在另一个类中实例化 Product 的实例:

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

但是当我尝试使用以下代码实例化一个 Product 数组时:

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

我收到一个编译错误:“(”预期 - 表达式的非法开头。请我需要帮助。

更新 我已将代码修改为:

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

但它仍然给我一个错误!

【问题讨论】:

    标签: java arrays inner-classes


    【解决方案1】:

    不可能创建 inner 类的对象,除非我们已经有了 外部类。这是因为 inner 类的对象悄悄地连接到构成它的 outer 类的对象。但是,如果你创建一个嵌套类(一个静态内部类),那么它就不需要对外部类对象的引用。

    但是,在创建 inner 类的数组时,情况并非如此。在创建内部类数组时,我们不能使用 outer 类的 Object 来引用内部类。因为,我们没有创建任何 inner 对象。我们只是在创建一个数组,它只是放置 inner 对象的地方。它不需要属于任何外部对象。

      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
    

    对于您的上下文,您需要执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多