John Ingram
John Ingram

Reputation: 164

Constructor chaining with array in Java

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.

Upvotes: 7

Views: 862

Answers (3)

malvern dongeni
malvern dongeni

Reputation: 681

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.

Upvotes: 6

Naomi
Naomi

Reputation: 5486

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)); 
}

Upvotes: 3

luk2302
luk2302

Reputation: 57204

That is possible via

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

Upvotes: 13

Related Questions