Constructor Overloadingin Java
● Constructor overloading in Java is a powerful feature that allows you to
define multiple constructors for a class, each with a different set of parameters.
This provides flexibility in how you create objects of that class, allowing you to
initialize them with different data or in different ways. Key Concepts:
● Multiple Constructors: A class can have multiple constructors with the same
name but different parameter lists (number of parameters, types of parameters,
or order of parameters).
● Constructor Signature: The constructor signature includes the constructor
name (which is always the class name) and the parameter list. The compiler uses
the signature to determine which constructor to call when you create an object.
● Object Initialization: Constructors are responsible for initializing the instance
variables (fields) of an object when it is created. Overloading constructors allows
you to provide different ways to initialize these variables. Benefits of Constructor
Overloading:
● Flexibility: You can create objects with different initial states depending on
the data available or the desired configuration.
● Code Reusability: You can avoid redundant code by calling one constructor
3.
Example:
public classRectangle {
private int width;
private int height;
// Constructor 1: No parameters (default constructor)
public Rectangle() {
width = 0;
height = 0;
}
// Constructor 2: Two parameters (width and height)
public Rectangle(int width, int height) {
this. width = width;
this. height = height;
}
}
// Constructor 3: One parameter (square)
public Rectangle(int side){ this(side, side);
// Calls constructor 2 to set both width and height
4.
}
// Method tocalculate area public int get Area()
return width * height;
public static void main(String[] args () ;
{
Rectangle rect1 = new Rectangle();
width 0 and height 0 Rectangle rect2 = new Rectangle(5, 10);
with width 5 and height 10
Rectangle rect3 = new Rectangle(7);
System .out. Print ln ("Area of rect1: " + rect1.getArea()); //
Output: 0
System .out .print ln ("Area of rect2: " + rect2.getArea()); //
Output: 50 System .out .print ln("Area of rect3: " +
rect3.getArea());
// Output: 49
}
}
5.
Explanation:
● The Rectangleclass has three constructors: The default constructor
○
initializes
both width and height to 0.
○ The second constructor takes two parameters to set the width and
height.
○ The third constructor takes one parameter (for a square) and calls the
second constructor using this(side, side) to set both width and height to t
same value
● The main method demonstrates how to create Rectangle objects using
different constructor
Rules for Constructor Overloading:
● Constructors must have the same name as the class.
● Constructors must have different parameter lists (either different
number of parameters,