What is Parameterized Constructor in Java: Simple Explanation and Example
parameterized constructor in Java is a special method used to create objects with specific initial values by passing arguments when the object is created. It allows setting different values for object properties at the time of creation instead of using default values.How It Works
Think of a parameterized constructor like ordering a custom sandwich at a deli. Instead of getting a plain sandwich, you tell the chef exactly what ingredients you want. Similarly, when you create an object in Java, a parameterized constructor lets you give specific values to the object's properties right away.
When you write a parameterized constructor, you define it with parameters (placeholders for values). When you create an object, you pass actual values to these parameters. The constructor then uses these values to set up the object’s state. This is different from a default constructor, which sets properties to fixed default values.
Example
This example shows a class Car with a parameterized constructor that sets the car's brand and year when creating a new car object.
public class Car { String brand; int year; // Parameterized constructor public Car(String brand, int year) { this.brand = brand; this.year = year; } public void displayInfo() { System.out.println("Brand: " + brand + ", Year: " + year); } public static void main(String[] args) { Car car1 = new Car("Toyota", 2020); Car car2 = new Car("Honda", 2018); car1.displayInfo(); car2.displayInfo(); } }
When to Use
Use a parameterized constructor when you want to create objects with different initial values easily and clearly. This is helpful when your objects represent things that have unique properties, like different cars, users, or products.
For example, in a shopping app, you might create product objects with different names and prices using a parameterized constructor. This saves time and makes your code cleaner by avoiding setting each property separately after creating the object.
Key Points
- A parameterized constructor takes arguments to set object properties when creating it.
- It helps create objects with different initial states easily.
- It improves code readability and reduces the need for multiple setter calls.
- If you define a parameterized constructor, Java does not provide a default constructor automatically.