Constructor Overloading in Java
beginner· OOP · Constructors
Problem
Constructor overloading means giving a class more than one constructor, each with a different parameter list, so an object can be created in more than one way depending on what information is available.
Create a Car class with one constructor that takes just a model name, and another that takes both a model and a year.
Input
new Car("Civic"), new Car("Accord", 2020)
Output
Civic (2024)
Accord (2020)
Java Program
Java
class Car {
String model;
int year;
Car(String model) {
this.model = model;
this.year = 2024; // default year when none is given
}
Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println(model + " (" + year + ")");
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
Car car1 = new Car("Civic");
Car car2 = new Car("Accord", 2020);
car1.display();
car2.display();
}
}Output
Civic (2024)
Accord (2020)
Core Logic
Declaring two constructors with different parameter counts lets Java pick the right one based on how many arguments a particular call actually supplies.
How It Works
- 1
Car(String model)takes only a model name and fills in2024as a default year. - 2
Car(String model, int year)takes both values directly, with no default needed. - 3
new Car("Civic")matches the single-argument constructor, since only one value is supplied. - 4
new Car("Accord", 2020)matches the two-argument constructor instead, since both values are supplied.
car1 ends up with year 2024 from the default, while car2 keeps the year 2020 it was given directly.💡
Key Point: Java chooses which constructor to run purely by matching the number and types of arguments at the call site — there's no need to name which constructor you mean.
Key Concepts
constructor overloadingmultiple constructorsdefault value