Java Reference
In-Depth Information
Calling a Constructor from another Constructor
A constructor may call another constructor of the same class. Let's consider the following
Test
class. It declares two
constructors; one accepts no parameters and one accepts an
int
parameter.
public class Test {
Test() {
}
Test(int x) {
}
}
Suppose you want to call the constructor with an
int
parameter from the constructor with no parameter. Your
first attempt, which is wrong, would be as follows:
public class Test {
Test() {
// Call another constructor
Test(103); // A compile-time error
}
Test(int x) {
}
}
The above code does not compile. Java has a special way to call a constructor from another constructor. You
must use the keyword
this
, as if it is the name of the constructor, to call a constructor from another constructor.
The following code calls the constructor with an
int
parameter from the constructor with no parameter using the
statement, “
this(103);"
. This is another use of the keyword
this
.
public class Test {
Test() {
// Call another constructor
this(103); // OK. Note the use of the keyword this.
}
Test(int x) {
}
}
There are two rules about calling a constructor from another constructor. The rules ensure that one constructor is
executed only once during the process of an object creation of a class.
•
If a constructor calls another constructor, it must be the first executable statement in the
constructor's body. This makes it easy for the compiler to check that a constructor has been
called and it has been called only once. For example, the following code will generate a
compiler error because a call to the constructor with
int
parameter
this(k)
is the second
statement inside the constructor's body, not the first statement.