Tuesday, May 20, 2008

What does a constructor do?

The constructor helps initializing the state of the object. So initially the implicit or the defined no-argument constructor of the super class is called so that the parent gets initialized in a proper manner.


One more restriction that is being imposed when a constructor is being defined is that call to any explicit super class constructor must be the first statement of all the constructors. So this might sound like a weird restriction at first but this rule guarantees the parent object to be in a valid state before the child object gets operational. This would help in avoiding the situations like this :


class Date{
public Date(){ date = setDate... }
String date;
}

// what if?
class DateViewer extends Date{
public DateViewer(){
System.out.println("The Date: " + date);
super();
}
}

Another thing that must be kept in mind while dealing with the constructors is that once you define a non-default constructor with non-zero arguments then and there the implicit constructor's definition inserted is removed from the code. So now if you have two classes X and Y such that
class Y
{
Y(int x,int y)
{

}
}

class X extends Y
{

}

Now this will result in a compilation error in the class X..Because the JVM tries to call the super() method while initializing the child object but since there is not implicit constructor for the parent class, this results in a error. Also see this amusing thread on sun forum:

http://forum.java.sun.com/thread.jspa?threadID=731805&start=0&tstart=0

No comments: