Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Constructor Chaining

Monday, April 15, 2024 7:06 PM

1. One constructor calling another constructor.


2. With the help of this() call statement we can perform constructor chaining.
3. this() call statement it is a control transfer statement.

public class Box


{
double length;
double width;
double area;

Box()
{
System.out.println("Box is getting ready...!");
} Box(double length, double width, double area)
Box(double length) {
{ this(length, width); //this.length = length; this.width = width;
this(); this.area = area;
this.length = length; System.out.println("Area is initialized...!!");
System.out.println("Length is initialized...!!"); }
}
Box(double length,double width)
{
this(length); //this.length = length;
this.width = width;
System.out.println("Width is initialized...!!");
Box(double length, double width)
}
{
Box(double length, double width, double area)
this(length); //this.length = length;
{
this.width = width;
this(length, width); //this.length = length; this.width
System.out.println("Width is initialized...!!");
= width;
}
this.area = area;
System.out.println("Area is initialized...!!");
}
public static void main(String[] args)
{
double length = 4.3; Box(double length)
double width = 5.6; {
Box b1 = new Box(length, width, length*width); this();
} this.length = length;
} System.out.println("Length is initialized...!!");
}

Box()
{
OUTPUT System.out.println("Box is getting ready...!");
}
Box is getting ready...!"
Length is initialized...!!
Width is initialized...!!
Area is initialized...!!

Order of Execution: -
1. Box()
2. Box(length)
3. Box(length, width)
4. Box(length, width, area)

Constructor Chaining Page 1

You might also like