Parameterized Constructor in Java
beginner· OOP · Constructors
Problem
A parameterized constructor takes arguments and uses them to set up an object's fields immediately, instead of leaving them at default values until set later.
Create a Car class whose constructor takes a model name and year, and initializes a new object with them directly.
Input
new Car("Mustang", 2023)
Output
Mustang (2023)
Java Program
Java
class Car {
String model;
int year;
Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println(model + " (" + year + ")");
}
}
public class ParameterizedConstructorDemo {
public static void main(String[] args) {
Car car = new Car("Mustang", 2023);
car.display();
}
}Output
Mustang (2023)
Core Logic
Passing the model and year straight into the constructor means a Car object is never left half-initialized — both fields are set the moment it's created.
How It Works
- 1
Car(String model, int year)declares a constructor that requires both values up front. - 2
this.model = model;andthis.year = year;assign the constructor's parameters to the object's own fields, usingthisto distinguish the field from the parameter of the same name. - 3
new Car("Mustang", 2023)supplies both arguments at the point of creation, running the constructor immediately. - 4By the time
display()is called, both fields already hold the values passed in — there's no separate setup step needed.
Creating
new Car("Mustang", 2023) sets model to "Mustang" and year to 2023 in one step, and display() prints "Mustang (2023)".💡
Key Point: Unlike a no-argument constructor that would leave model and year at their default values (null and 0), a parameterized constructor forces every caller to supply real values before an object can even exist.
Key Concepts
constructorconstructor argumentsthis keyword