I can't seem to figure out how to chain constructors when the constructor I'm trying to call is supposed to use values passed to the constructor I'm calling it from.
I tried this:
public BoundingBox(Point a, Point b)
{
Point[] points = {a, b}
this(points);
}
but I'm told that the call to this
must be on the first line of the constructor.
I'm trying to call this constructor
public BoundingBox(Point[] input)
{
//do some work
}
Ideally, I could chain these constructors. Otherwise, I may have to restructure my code.
For example, an array can be supplied to the ArrayList constructor, or the List. of() and Arrays.
Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.
Java Constructor Chaining in the Same Class You can create multiple constructors in the same class, each with a different number of arguments that it accepts. To call one of the constructors in another constructor (of the same class), use the keyword this().
Constructor chaining in Java is a technique of calling one constructor from within another constructor by using this and super keywords. The keyword “this” is used to call a constructor from within another constructor in the same class.
Prerequisite – Constructors in Java. Constructor chaining is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in same class.
Why do we need constructor chaining ? This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable.
Initializing an array in the constructor does not make sense if it is initialized with default values because Java does this implicitly. In this example, we declared an array in the class and then initialized it within a constructor, So, the array get initialized when the constructor is called. See the example below.
A constructor is a piece of code that is used to initialize the objects of a class. Constructors have similar syntax as methods but constructors do not have return types. Constructors have the same name as the class name.
That is possible via
this(new Point[] {a, b});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With