Sub topic 6
Overloading constructors and delegating with this
A constructor is the part of a Java class that sets up a new object. An object is a single instance of a class. When you create an object with new, Java calls a constructor for that class.
Sometimes there is more than one useful way to create an object. For example, you might want a counter that starts at zero, or one that starts at a number you choose.
Constructor overloading lets a class offer these choices. Constructor delegation lets one constructor pass work to another, so you do not have to repeat the setup code.
The examples use Java 17 or 21, with preview features off.
Offer more than one constructor
An overloaded constructor is one of two or more constructors in the same class that have different parameter lists. A parameter is a named input in a constructor’s definition. An argument is the value you pass when you call it.
Here is a complete example. Save it as Counter.java.
class Counter {
private int value;
Counter() {
this(0);
}
Counter(int initialValue) {
if (initialValue < 0) {
throw new IllegalArgumentException(
"Initial value must be nonnegative"
);
}
this.value = initialValue;
}
void increment() {
value++;
}
int getValue() {
return value;
}
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter(5);
first.increment();
second.increment();
System.out.println(first.getValue());
System.out.println(second.getValue());
}
}Compile the file with javac Counter.java, then run it with java Counter. It prints 1 and then 6, each on its own line.
The class has two constructors:
| Constructor | Parameter list | Example call |
|---|---|---|
| `Counter()` | No parameters | `new Counter()` |
| `Counter(int initialValue)` | One `int` parameter | `new Counter(5)` |
The word int means a whole-number type. In new Counter(5), the argument 5 is passed to the parameter named initialValue.
The field value stores each counter’s number. A field is a variable that belongs to an object. The word private means code outside the class cannot access that field directly. The methods increment() and getValue() let the example change and read it.
Follow the delegation
Look at the no-argument constructor, a constructor with no parameters:
Counter() calls this(0).
The call this(0) tells Java to run the Counter(int initialValue) constructor for the same object. It passes 0 as the argument. This is delegation: one constructor hands part of its work to another.
Here is what happens for new Counter():
- Java creates a
Counterobject and callsCounter(). Counter()delegates toCounter(int initialValue)with the argument0.- The second constructor checks the argument and sets
valueto0. - Control returns to
Counter(), which then finishes.
For new Counter(5), Java calls the constructor with the int parameter directly. It checks 5 and sets value to 5.
The call to this(0) does not create a second counter. Both constructors work on the same object.
Why delegate?
Without delegation, both constructors might need to set up value. If the setup later changes, you would have to remember to update both places.
Here, the constructor with an int parameter has the shared setup. It also checks that the starting value is not negative. If it is negative, the constructor throws an IllegalArgumentException. An exception is a signal that something went wrong.
Because Counter() delegates to that constructor, the default value of 0 goes through the same check. For example, new Counter(-2) does not produce a usable counter; it throws the exception instead.
Understand which constructor Java calls
Java chooses an overload from the arguments in the call. It looks at their number and types.
In the Counter example:
new Counter()matches the constructor with no parameters.new Counter(5)matches the constructor with oneintparameter.new Counter(2.5)does not match either constructor. The value2.5has typedouble, a type for numbers with fractional parts, notint.
The compiler checks these calls before the program runs. A compiler is the tool that checks Java source code and turns it into a form Java can run. If no constructor matches, compilation fails.
A constructor’s signature is its parameter types in order. Constructors in the same class need different signatures to be overloads.
For example, a constructor with parameters (int size, String label) has a different signature from one with (String label, int size). A String is a value used to hold text. The order of the types differs, so Java can tell those constructors apart.
Changing only a parameter name does not make a new signature. Counter(int start) and Counter(int initialValue) both have the signature (int). A class cannot declare both.
Chain several constructors
A constructor can delegate to a constructor that delegates again. This is called a constructor chain.
Save the following example as Greeting.java. Its print statements show the order in which the constructor bodies finish.
class Greeting {
private String name;
private String punctuation;
Greeting() {
this("friend");
System.out.println("Finished no-argument constructor");
}
Greeting(String name) {
this(name, "!");
System.out.println("Finished one-argument constructor");
}
Greeting(String name, String punctuation) {
this.name = name;
this.punctuation = punctuation;
System.out.println("Finished two-argument constructor");
}
String message() {
return "Hello, " + name + punctuation;
}
public static void main(String[] args) {
Greeting greeting = new Greeting();
System.out.println(greeting.message());
}
}Compile it with javac Greeting.java, then run it with java Greeting. The output is:
Finished two-argument constructorFinished one-argument constructorFinished no-argument constructorHello, friend!
The constructors are called in the opposite order from the first three messages. Each constructor waits for the one it calls to finish before it continues.
The first constructor supplies the name "friend". The second supplies the punctuation "!". The third puts both values in fields. Each constructor in the chain works on the same Greeting object.
Recognize two uses of this
In these examples, this refers to the current object: the object being set up.
The spelling after this matters:
this(0)calls another constructor in the same class.this.namerefers to the current object’snamefield.
In this.name = name, the parameter and field are both named name. The expression on the left, this.name, means the field. The expression on the right, name, means the parameter. The assignment puts the parameter’s value into the field.
In the Counter example, this.value = initialValue also names the current object’s field. The field and parameter have different names, so value = initialValue would work there too. Using this.value makes it clear that value is a field.
Rules and common mistakes
In Java 17 and 21, a this(...) constructor call must be the first statement in the constructor body. You cannot print a message or assign a field before it. You can, however, do work after the delegated constructor returns, as the Greeting example does.
A constructor chain must also reach a constructor that does not delegate with this(...). It cannot loop back to a constructor already in the chain. Java rejects such a loop because the setup could never finish.
The constructor you call with this(...) must have a matching parameter list. For example, this(0) needs a constructor that can accept an int. If the class has only a no-argument constructor, that call will not compile.
Finally, keep the no-argument choice in mind. If you write no constructors, Java can supply a no-argument constructor. Once you declare any constructor, Java does not supply one automatically. If you want both new Counter() and new Counter(5) to work, declare both constructors, as the example does.
Exercises
Exercise
In the Counter example, what value does getValue() return after you create a counter with new Counter(7) and call increment() once?
Show answer
It returns 8. The int constructor sets the value to 7, and increment() adds 1.
Exercise
Can one class declare both Counter(int start) and Counter(int initialValue)? Why?
Show answer
No. Both constructors have the same parameter type, int. Changing the parameter name does not create a different signature.
Exercise
In the Greeting example, which constructor prints its “Finished” message first when you call new Greeting()?
Show answer
The two-argument constructor prints first. The other constructors wait for their delegated calls to finish.
Exercise
Why does Counter() use this(0) instead of setting value itself?
Show answer
It sends the default value through the same constructor that checks and stores a supplied starting value, so that setup is kept in one place.