Constructor overloading in Java allows a class to have more than one constructor with different parameter lists. This gives you the flexibility to initialize objects in different ways. Constructor overloading provides the benefit of:
- Multiple Initialization Options: You can initialize an object in different ways depending on the data available.
- Cleaner Code: Avoids redundant code by allowing various constructors instead of multiple
set
methods.
Constructor overloading works by defining multiple constructors within a class, each with a unique set of parameters. Java then selects the appropriate constructor based on the arguments passed when an object is created.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class Car { String model; int year; // Default constructor public Car() { this.model = "Unknown"; this.year = 2020; } // Constructor with one parameter public Car(String model) { this.model = model; this.year = 2020; } // Constructor with two parameters public Car(String model, int year) { this.model = model; this.year = year; } public void display() { System.out.println("Model: " + model + ", Year: " + year); } public static void main(String[] args) { Car car1 = new Car(); // Calls default constructor Car car2 = new Car("Toyota"); // Calls constructor with one parameter Car car3 = new Car("Honda", 2021); // Calls constructor with two parameters car1.display(); car2.display(); car3.display(); } } |
Output
1 2 3 |
Model: Unknown, Year: 2020 Model: Toyota, Year: 2020 Model: Honda, Year: 2021 |
In the above example:
- Default Constructor:
Car()
initializes themodel
to"Unknown"
and theyear
to2020
. - Parameterized Constructors:
Car(String model)
initializes themodel
with a given value, and sets theyear
to2020
.Car(String model, int year)
allows both themodel
andyear
to be specified.