Computer Applications
Answer
The process of creating more than one constructor with the same name but with different parameter declarations is called constructor overloading.
The below example shows constructor overloading being used to create a class having three constructors:
public class Rectangle
{
int length;
int width;
//Constructor without any parameters
public Rectangle() {
System.out.println("Invoking constructor with no parameters");
length = 20;
width = 15;
}
// Constructor with one parameter
public Rectangle(int len) {
System.out.println("Invoking constructor with one parameter");
length = len;
width = 20;
}
// Constructor with two parameters
public Rectangle(int len, int wd) {
System.out.println("Invoking constructor with two parameters");
length = len;
width = wd;
}
public void Area() {
int area = length * width;
System.out.println("Length = " + length);
System.out.println("Width = " + width);
System.out.println("Area = " + area);
}
public static void main(String args[]) {
Rectangle rect1 = new Rectangle();
rect1.Area();
Rectangle rect2 = new Rectangle(30);
rect2.Area();
Rectangle rect3 = new Rectangle(30, 10);
rect3.Area();
}
}