我是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)
为什么需要两个构造函数?这是一个特别糟糕的例子吗?有人可以解释一下。