Invoking Overloaded Constructors Through this( )
In Java this keyword can call the overloaded constructors.
The general form is shown here:
this(arg-list)
When this( ) is executed, the overloaded constructor that matches the arg-list is executed first.
The call to this( ) must be the first statement within the constructor.
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)
}
}
Home
Java Book
Class
Java Book
Class
Constructors:
- Using Constructors
- Overloading Constructors
- Invoking Overloaded Constructors Through this( )