ImagineBaggins
ImagineBaggins

Reputation: 130

Is it possible for a constructor to accept a number of parameters defined by a previous parameter?

Say you have the following class:

public class MyClass {

    public MyClass() {
    }
}

I want to be able to pass a definable amount of parameters in a constructor, something like this:

    public MyClass(int parameters, int /* "parameters" amount of integers here*/) {
    }

I know I can use the ellipsis operator, but then the constructor will accept more or less parameters than the int "parameters". Is there a way to do that?

Upvotes: 4

Views: 299

Answers (3)

ZhongYu
ZhongYu

Reputation: 19682

I'm gussing that the first argument will be a named constant, and it differentiates different cases

new MyClass(CASE_ONE, p1);

You can use factory methods

public static MyClass createCaseOne(int p1){ ... }

public static MyClass createCaseTwo(int p1, int p2){ ... }

public static MyClass createCaseThree(int p1, int p2, int p3){ ... }

...

Upvotes: 0

Maroun
Maroun

Reputation: 95998

public MyClass(int parameters, int /* "parameters" amount of integers here*/) { }

See this link about Defining Methods:

The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, ()

The parameters don't tell you how much data it expect, it tell you the data type.

If you want, you can check the amount inside the constructor at runtime:

if(parametersAmount != desiredAmount) ...

Upvotes: 1

rgettman
rgettman

Reputation: 178303

You can't enforce this restriction in the Java compiler, but you can enforce it an runtime, by throwing an IllegalArgumentException:

public MyClass(int numParameters, int... parameters) {
    if (numParameters != parameters.length)
       throw new IllegalArgumentException("Number of parameters given doesn't match the expected amount of " + numParameters);
    // Rest of processing here.
}

This uses Java's varargs feature to accept an unknown number of parameters.

Note: I've renamed the parameters a bit for clarity.

Upvotes: 5

Related Questions