内部类和两个构造函数

时间:2013-09-07 23:22:25

标签: java

我是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)

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

2 个答案:

答案 0 :(得分:2)

这个

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

初始化FactoryInner数组lastIndex中索引FactoryInner的{​​{1}}引用。

fi

初始化FactoryInner[] fi = new FactoryInner[3]; fi数组。注意方括号FactoryInner

在初始化其元素之前,必须先初始化数组。否则,您尝试访问[]数组引用的成员并获得null

答案 1 :(得分:2)

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

FactoryInner[] fi = new FactoryInner[3]; 

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

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