7

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.

3 Answers 3

13

That is possible via

this(new Point[] {a, b}); 
Sign up to request clarification or add additional context in comments.

Comments

6

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.

3 Comments

@malverndongeni usually a better definition is public BoundingBox(Point first, Point ... rest){
@Eugene you are right.but that approach will require us to define no argument constructor as this case will fail new BoundingBox() moreover,It will force us to supply first Point. *NB there is a brief description of how varargs works which is inline with your approach
The argument for Point first, Point ... rest depends on the use case. If a no-arg constructor is valid, e.g. you can create a BoundingBox without any points then using only one vararg argument is perfectly fine. If on the other hand you always have to have at least one point then you may want to use first, rest approach or even first, second, third, rest depending how many points are the minimum.
3

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

1 Comment

I really like the static factory method approach, come in handy when creating more complicated objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.