1

我是java的新手。我在互联网上的某个地方遇到了这段代码。

  class FactoryOuter {

  FactoryInner[] fi = new FactoryInner[3];
  private int lastIndex = 0;
  private int x = 0;

  public FactoryOuter(int x)
  {
    this.x = x;
  }

  public int getX()
  {
    return x;
  }

  public void addInner(int y)
  {
    if (lastIndex < fi.length)
    {
      fi[lastIndex++] = new FactoryInner(y);
    }
    else throw new RuntimeException("FactoryInner array full");
  }

  public void list()
  {
    for (int i = 0; i < fi.length; i++)
    {
      System.out.print("I can see into the inner class where y = " +
                       fi[i].y + " or call display: ");
      fi[i].display();
    }
  }

  public class FactoryInner
  {
    private int y;
    private FactoryInner(int y)
    {
      this.y = y;
    }
    public void display()
    {
      System.out.println("FactoryInner x =  " + x + " and y = " + y);
    }
  }
}

public class FactoryInnerOuter
{

    public static void main(String[] args)
    {
        FactoryOuter fo = new FactoryOuter(1);
        fo.addInner(101);
        fo.addInner(102);
        fo.addInner(103);
        fo.list();
        //fo.addInner(104);
    }
}

上面代码的输出如下所示

I can see into the inner class where y = 101 or call display: FactoryInner x =  1 and y = 101
I can see into the inner class where y = 102 or call display: FactoryInner x =  1 and y = 102
I can see into the inner class where y = 103 or call display: FactoryInner x =  1 and y = 103

我的问题如下

1)我看到FactoryInner类的构造函数被调用了两次。第一个实例显然调用了一个默认构造函数,如下所示。

 FactoryInner[] fi = new FactoryInner[3];

第二个实例调用代码中定义的构造函数。

fi[lastIndex++] = new FactoryInner(y);

为什么代码需要两个构造函数?如果我更换

FactoryInner[] fi = new FactoryInner[3]; with

FactoryInner[] fi;

我确实收到以下错误。

Exception in thread "main" java.lang.NullPointerException
    at FactoryOuter.addInner(FactoryInnerOuter.java:19)
    at FactoryInnerOuter.main(FactoryInnerOuter.java:56)

为什么需要两个构造函数?这是一个特别糟糕的例子吗?有人可以解释一下。

4

2 回答 2

2

这个

fi[lastIndex++] = new FactoryInner(y);

初始化数组FactoryInner中索引处lastIndex的引用。FactoryInnerfi

这个

FactoryInner[] fi = new FactoryInner[3]; 

初始化fi FactoryInner数组。注意方括号,[].

您必须先初始化数组,然后才能初始化其元素。否则,您尝试访问null数组引用的成员并获取NullPointerException.

于 2013-09-07T23:25:10.173 回答
2

第一个不是对构造函数的调用。在这里,您正在初始化一个 FactoryInner 对象数组,其中包含三个对象的空间:

FactoryInner[] fi = new FactoryInner[3]; 

在这里,您将实际的 FactoryInner 对象放入数组中,因此您需要为构造函数赋值,因为现在您实际上是从类 FactoryInner 初始化对象:

fi[lastIndex++] = new FactoryInner(y);
于 2013-09-07T23:33:27.913 回答