user2426316
user2426316

Reputation: 7331

How can I avoid creating lots overloaded methods?

I have a method that I would like to use in different occasions. That means that I want to use the method but each time pass in a different amount of arguments:

Consider this example:

public checkInput(Object a, Object b, Object c, Object d) {
    a.someMethod();
    b.someMethod();
    c.someMethod();
    d.someMethod();
}

Now I can only use this method checkInput(...) when I pass in 4 parameters. However, there are occasions where I only can pass in two parameters for example.

If I would like to call the method like this checkInput(a, b, null, null); I will get a NullPointerException.

So now I am wondering, will I have to use overloading in this case, meaning that I will have to create

public checkInput(Object a) {
    a.someMethod();
}

public checkInput(Object a, Object b) {
    a.someMethod();
    b.someMethod();
}

... and so on.

Upvotes: 2

Views: 91

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213411

You can define Variable arity method:

public checkInput(Object... args) {
    // args is nothing but an array.
    // You can access each argument using indices args[0], args[1], ...
}

Now, you can invoke this method using any number of arguments:

checkInput(obj);
checkInput(obj1, obj2);

Using varargs is similar to using arrays as parameter. But it gives you the flexibility of passing parameters, without creating an array.

But be careful, since the type of var-args is Object, it will take any type of argument. You should do appropriate check before using them. Also, you can only have a single vararg parameter in your method, and that too should come last in the list of parameter.

Upvotes: 9

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

No. Simply re-use the four param method as

public checkInput(Object a) {
    checkInput(a, null, null, null);
}

public checkInput(Object a, Object b) {
    checkInput(a, b, null, null);
}

Upvotes: 0

Related Questions