Constructor overloading in Java

What is constructor overloading ?

Constructor overloading is a concept in object-oriented programming that allows a class to have multiple constructors with different parameter lists. This feature provides flexibility in creating objects by enabling instances to be initialized in various ways, depending on the parameters passed during object creation.

Example of Constructor Overloading In Java :

Here’s an example in a Java-like pseudocode to illustrate constructor overloading:

public class Main {
public static void main(String[] args) {
// Creating objects using different constructors
Car defaultCar = new Car(); // Default constructor
Car customCar1 = new Car("Toyota", "Camry"); // Constructor with make and model
Car customCar2 = new Car("Honda", "Civic", 2022); // Constructor with make, model, and year

// Accessing and printing object properties
System.out.println(defaultCar.toString());
System.out.println(customCar1.toString());
System.out.println(customCar2.toString());

// Modifying object properties using setters
defaultCar.setMake("Ford");
defaultCar.setModel("Mustang");
defaultCar.setYear(2021);

// Accessing and printing modified object
System.out.println("Modified Default Car: " + defaultCar.toString());
}
}

class Car {
// Fields or attributes
private String make;
private String model;
private int year;

// Default constructor
public Car() {
this.make = "Unknown";
this.model = "Unknown";
this.year = 0;
}

// Constructor with parameters for make and model
public Car(String make, String model) {
this.make = make;
this.model = model;
this.year = 0; // Default year when not specified
}

// Constructor with parameters for make, model, and year
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Getter for make
public String getMake() {
return make;
}

// Setter for make
public void setMake(String make) {
this.make = make;
}

// Getter for model
public String getModel() {
return model;
}

// Setter for model
public void setModel(String model) {
this.model = model;
}

// Getter for year
public int getYear() {
return year;
}

// Setter for year
public void setYear(int year) {
this.year = year;
}

// toString method for string representation
@Override
public String toString() {
return "Car{" +
"make='" + make + '\'' +
", model='" + model + '\'' +
", year=" + year +
'}';
}
}

Output :

Car{make='Unknown', model='Unknown', year=0}
Car{make='Toyota', model='Camry', year=0}
Car{make='Honda', model='Civic', year=2022}
Modified Default Car: Car{make='Ford', model='Mustang', year=2021}

 

Leave a Reply

Your email address will not be published. Required fields are marked *