This class contains three constructors, each of which initializes the values of a and b. The
first is passed individual values for a and b. The second is passed just one value, which is
assigned to both a and b. The third gives a and b default values of zero.
By using this( ), it is possible to rewrite MyClass as shown here:
class MyClass {
int a;
int b;
// initialize a and b individually
MyClass(int i, int j) {
a = i;
b = j;
}
// initialize a and b to the same value
MyClass(int i) {
this(i, i); // invokes MyClass(i, i)
}
// give a and b default values of 0
MyClass( ) {
this(0); // invokes MyClass(0)
}
}
In this version of MyClass, the only constructor that actually assigns values to the a and
b fields is MyClass(int, int). The other two constructors simply invoke that constructor
(either directly or indirectly) through this( ). For example, consider what happens when this
statement executes:
MyClass mc = new MyClass(8);
The call to MyClass(8) causes this(8, 8) to be executed, which translates into a call to
MyClass(8, 8), because this is the version of the MyClass constructor whose parameter list
matches the arguments passed via this( ). Now, consider the following statement, which
uses the default constructor:
MyClass mc2 = new MyClass();
In this case, this(0) is called. This causes MyClass(0) to be invoked because it is the
constructor with the matching parameter list. Of course, MyClass(0) then calls MyClass(0,
0) as just described.
One reason why invoking overloaded constructors through this( ) can be useful is that it
can prevent the unnecessary duplication of code. In many cases, reducing duplicate code
decreases the time it takes to load your class because often the object code is smaller. This is
especially important for programs delivered via the Internet in which load times are an
issue. Using this( ) can also help structure your code when constructors contain a large
amount of duplicate code.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home