Java Reference
In-Depth Information
overloaded constructors, typically they include one constructor that carries out
basic initialization tasks and then each of the other constructors does optional
tasks. Rather than repeating the initialization code in each constructor, an over-
loaded constructor can invoke this() to call another constructor to carry out
the initialization tasks.
Forexample, the following code shows a class with two constructors:
class Test {
int x,y;
int i,k;
Test (int a, int b) {
x = a;
y = b;
}
Test (int a, int b, int c, int d) {
this (a,b);// Must be in first line
i = c;
k = d;
}
}
The first constructor explicitly initializes the values of two of the data variables
(the other two variables receive the default 0 value for integers). The second
constructor needs to initialize the same two variables plus two more. Rather than
include redundant code, the second constructor first invokes this (a, b) ,
which executes the first constructor, and then initializes the other two variables.
The parameter list in the invocation of this() must match that of the desired
constructor (every constructor must have a unique parameter list in number and
types). In this case, this (a, b) matches that of the first constructor with two
int arguments. The invocation of this() must be the first executable statement
in a constructor and cannot be used in a regular method.
4.3.2 super()
There is another special method named super() . When we create an instance of
a subclass, its constructor plus a constructor in each of its superclasses are invoked
(we discuss below the invocation sequence of the constructors). If there are mul-
tiple overloaded constructors somewhere in the chain, we might care which con-
structor gets used. We choose which overloaded superclass constructor we want
with super() .
Forexample, in the following code, class Test2 extends class Test1 , class
Test1 has a one-argument constructor and a two-argument constructor while
 
Search WWH ::




Custom Search