If your arguments are the same type you could use varargs:
public int something(int... args) {
int a = 0;
int b = 0;
if (args.length > 0) {
a = args[0];
}
if (args.length > 1) {
b = args[1];
}
return a + b
}
but this way you lose the semantics of the individual arguments, or
have a method overloaded which relays the call to the parametered version
public int something() {
return something(1, 2);
}
or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:
class FoodBuilder {
int saltAmount;
int meatAmount;
FoodBuilder setSaltAmount(int saltAmount) {
this.saltAmount = saltAmount;
return this;
}
FoodBuilder setMeatAmount(int meatAmount) {
this.meatAmount = meatAmount;
return this;
}
Food build() {
return new Food(saltAmount, meatAmount);
}
}
Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();
Then work with the Food object
int doSomething(Food f) {
return f.getSaltAmount() + f.getMeatAmount();
}
The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.