Using this Keyword in Constructors in Java


Write a program that uses the this keyword to call one constructor from another

This Java code defines a class called Rectangle. In this class, rectangles are represented by their length and width attributes. There are two constructors provided:

  • The first constructor takes a single parameter, side, which is used to create a square by setting both the length and width to the value of side. This constructor internally calls the second constructor.
  • The second constructor takes two parameters, l and w, representing the length and width of a rectangle, respectively. It initializes the length and width attributes with the provided values and then prints out the length and width of the rectangle.

In the main method, an instance of Rectangle is created using the constructor that takes a single parameter, which creates a square with sides of length 7. When this instance is created, the length and width of the square are printed, showing that both are 7.

Source Code

class Rectangle
{
	int length, width;
 
	Rectangle(int side)
	{
		this(side, side);
	}
 
	Rectangle(int l, int w)
	{
		length = l;
		width = w;
		System.out.println("Length : " + length);
		System.out.println("Width : " + width);
	}
 
	public static void main(String[] args)
	{
		Rectangle square = new Rectangle(7);
	}
}

Output

Length : 7
Width : 7