Carson
Carson

Reputation: 1277

Can I have a Java method have params but doesn't require an arguement to be passed in?

So I have a program where you need to call a get method to get two items in an object. I thought, what if I could just have it so if the user passes in nothing with the arguement...

x.getItem();

It would work and just return one of the two items.

But if they wanted a specific item...

x.getItem(0); or x.getItem(1);

Is this possible in Java? I just didn't want 0 to be random and 1 and 2 to be default...because that could get confusing to read later.

Upvotes: 0

Views: 296

Answers (1)

Rob
Rob

Reputation: 6507

It sounds like you actually want is two methods:

private A[] a = new A[2];
public A getItem() {
    return a[new Random().nextInt(1)];
}
public A getItem(int index) {
    return a[index];
}

Given that the parameters are different for the two methods, you can use the same name (because the compiler can distinguish which one you are calling depending on the actual parameters).

If you were to implement this with some fakey optional parameter, your single method would be more complex - it would have both ways of looking up the return value plus the logic to decide that the parameter had been omitted. The two methods is a nice, clean solution.

Upvotes: 1

Related Questions