explain the concept of constructor overloading in Java? and give examples?
Constructor overloading in Java is a feature that allows a class to have more than one constructor with different parameter lists. This means that you can create multiple constructors in a class, each with a different number of parameters or different types of parameters. The appropriate constructor is called based on the arguments passed when an object of the class is created.
void
.Here’s a simple example to illustrate constructor overloading in Java:
class Rectangle {
private int length;
private int width;
// Constructor with no parameters
public Rectangle() {
this.length = 1; // default length
this.width = 1; // default width
}
// Constructor with one parameter
public Rectangle(int side) {
this.length = side; // square
this.width = side;
}
// Constructor with two parameters
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
// Method to calculate area
public int area() {
return length * width;
}
// Method to display dimensions
public void display() {
System.out.println("Length: " + length + ", Width: " + width);
}
}
public class Main {
public static void main(String[] args) {
// Using the constructor with no parameters
Rectangle rect1 = new Rectangle();
rect1.display(); // Output: Length: 1, Width: 1
System.out.println("Area: " + rect1.area()); // Output: Area: 1
// Using the constructor with one parameter
Rectangle rect2 = new Rectangle(5);
rect2.display(); // Output: Length: 5, Width: 5
System.out.println("Area: " + rect2.area()); // Output: Area: 25
// Using the constructor with two parameters
Rectangle rect3 = new Rectangle(4, 6);
rect3.display(); // Output: Length: 4, Width: 6
System.out.println("Area: " + rect3.area()); // Output: Area: 24
}
}
When you create an object of the Rectangle
class, the Java compiler determines which constructor to call based on the number and type of arguments provided. This flexibility allows for more readable and maintainable code.