Constructor chaining with array in Java

That is possible via

this(new Point[] {a, b}); 

You can replace the two constructor with the following that uses Varargs

public BoundingBox(Point ... input){
    //do some work
}

Brief about Varargs

a method may use a vararg parameter (variable argu- ment) as if it is an array. It is a little different than an array, though. A vararg parameter must be the last element in a method’s parameter list. This implies you are only allowed to have one vararg parameter per method.

When calling a method with a vararg parameter, you have a choice. You can pass in an array, or you can list the elements of the array and let Java create it for you. You can even omit the vararg values in the method call and Java will create an array of length zero for you.


You can use a static function that creates the array

static private Point[] createPointArray(Point a, Point b) 
{ 
    Point[] points = {a, b}
    return points;
}

public BoundingBox(Point a, Point b)
{
    this(createPointArray(a,b)); 
}

Tags:

Java