Overloaded constructors are very common in java because they provide several ways to create an object of a particular class. It also allow you to create and initialize an object by using different types of data.
{
int height;
int width;
Square()
{
height = 0;
width = 0;
}
Square(int side)
{
height = width = side;
}
Square(int sideh, int sidew)
{
height = sideh;
width = sidew;
}
}
class ImplSquare
{
public static void main(String args[])
{
Square sObj1 = new Square();
Square sObj2 = new Square(5);
Square sObj3 = new Square(2,3);
System.out.println("Variable values of object1 : ");
System.out.println("Object1 height = " + sObj1.height);
System.out.println("Object1 width = " + sObj1.width);
System.out.println("");
System.out.println("Variable values of object2 : ");
System.out.println("Object2 height = " + sObj2.height);
System.out.println("Object2 width = " + sObj2.width);
System.out.println("");
System.out.println("Variable values of object3 : ");
System.out.println("Object3 height = " + sObj3.height);
System.out.println("Object3 width = " + sObj3.width);
}
}
Output
Variable values of object1 :
Object1 height = 0
Object1 width = 0