Constructor Overloading in Java

December 25, 2022
Cover image for Constructor Overloading in Java

Similar to method overloading, constructor overloading is used when you want to call the constructor by passing in different parameters.

Constructor Overloading Example

Consider an example of a MessageCreator class that has a method to print out a greeting and a message. By declaring the constructor with different number of parameters, we can alter the message greeting and body.

class MessageCreator {
String greeting;
String body;
Example() {
this.greeting = "Hello.";
this.body = "This is a blank message.";
}
Example(String greeting) {
this.greeting = greeting;
this.body = "This is a blank message.";
}
Example(String greeting, String body;) {
this.greeting = greeting;
this.body = body;
}
public void printMessage() {
System.out.println(greeting + " " + body);
}
}

Alternatively, we could use this to write the constructor bodies as:

class MessageCreator {
String greeting;
String body;
MessageCreator() {
this("Hello.", "This is a blank message.");
}
MessageCreator(String greeting) {
this(greeting, "This is a blank message.");
}
MessageCreator(String greeting, String body;) {
this.greeting = greeting;
this.body = body;
}
public void printMessage() {
System.out.println(greeting + " " + body);
}
}

An object can be created and called as the following:

class Main {
public static void main(String[] args) {
MessageCreator messageCreator = new MessageCreator();
messageCreator.printMessage(); // Hello. This is a blank message.
messageCreator = new MessageCreator("Hi!");
messageCreator.printMessage(); // Hi!. This is a blank message.
messageCreator = new MessageCreator("Hi!", "This is constructor overloading.");
messageCreator.printMessage(); // Hi! This is constructor overloading.
}
}

Conclusion

Constructor overloading is useful when you want to create an instance of a class by passing in different parameters. We can have finer control on what code will execute when the constructor is called with different parameters.