Saturday, 7 September 2013

Inner class and two constructors

Inner class and two constructors

I am new to java.I came across this code somewhere on the internet.
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);
}
}
The output of the above code is given below
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
My questions are as follows
1) I see the constructor of FactoryInner class being called twice.The
first instance apparently calls a default constructor as shown below.
FactoryInner[] fi = new FactoryInner[3];
The second instance calls the constructor that is defined in the code.
fi[lastIndex++] = new FactoryInner(y);
Why does the code need two constructors? If I replace
FactoryInner[] fi = new FactoryInner[3]; with
FactoryInner[] fi;
I do get the following errors.
Exception in thread "main" java.lang.NullPointerException
at FactoryOuter.addInner(FactoryInnerOuter.java:19)
at FactoryInnerOuter.main(FactoryInnerOuter.java:56)
Why are two construcors needed ? Is this a particulary bad example? Could
someone please explain.

No comments:

Post a Comment