A constructor can call another constructor from the same class. This is usually done when a constructor duplicates some of the behavior of an existing constructor. In order to refer to another constructor in the same class, use this as the method name, followed by appropriate arguments enclosed in pair of parentheses, if necessary. Java requires that the call to this () can be used in a constructor and must be the first statement in the constructor followed by any other relevant code.
class Circle
{
int x,y; //x,y coordinates of circle
int radius; //radius of circle
Circle()
{
radius=1;
}
Circle(int xl, int yl)
{
this();
x = xl;
y = yl;
}
Circle(int xl, int yl,int r)
{
this(xl,yl);
radius = r;
}
void area()
{
System.out.println("Area of Circle is : "+(Math.PI * radius * radius));
}
}
class CallingConstructor
{
public static void main(String[] args)
{
Circle cl = new Circle(); //call no arg constructor
cl.area();
Circle c2 = new Circle(2,3); // calls two arg constructor
c2.area();
Circle c3 = new Circle (2,3,4); //calls three arg constructor
c3.area ();
}
}
The class Circle contains three constructors : no parameter constructor, two parameter constructor and three-parameter constructor.
The statement,
Circle cl = new Circle();
calls a zero parameter constructor. Here radius is initialized to Iand the coordinates x and y will be set a default value 0 .
The statement,
Circle c2 = new Circle(2,3);
calls a two parameter constructor. The statement this () ; on execution causes the zero-parameter constructor to be executed, as a result of which radius field is set to 1. After this, the other statement; in its body are executed which sets x and y fields with the values specified by the user.
The statement,
Circle c3 = new Circle(2,3,4);
calls a three parameter constructor. The statement this (xl ,yl) ; on execution causes the two parameter constructor to be executed and control shifts there. The statement this () ; in its body further calls a zero parameter constructor which initializes radius to 1 and sets x and y with default values (0 each). These values of x and yare overwritten in the body of the two-parameter constructor which are now set to xl (=2) and yl(=3). When the control shifts back to the next statement in the body of three parameter constructor, the value of radius is overwritten and radius is initialized to 4.