如何设置默认方法参数值?

Nik*_*lin 12 java parameters methods default-value

是否可以在Java中设置默认方法参数值?

示例:如果有方法

public int doSomething(int arg1, int arg2)
{
//some logic here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是否可以修改给定的方法,以便能够使用和不使用参数调用它?

例:

doSomething(param1, param2);
doSomething();
Run Code Online (Sandbox Code Playgroud)

谢谢!

And*_*are 48

您可以通过方法重载来完成此操作.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}
Run Code Online (Sandbox Code Playgroud)

通过创建此无参数方法,您允许用户使用您在无参数方法的实现中提供的默认参数调用parameterfull方法.这称为重载方法.


aka*_*okd 15

如果您的参数类型相同,则可以使用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
}
Run Code Online (Sandbox Code Playgroud)

但是这样你就失去了各个参数的语义,或者

有一个方法重载,它将调用中继到参数化版本

public int something() {
  return something(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

或者如果该方法是某种初始化过程的一部分,您可以使用构建器模式:

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();
Run Code Online (Sandbox Code Playgroud)

然后使用Food对象

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}
Run Code Online (Sandbox Code Playgroud)

构建器模式允许您稍后添加/删除参数,而不需要为它们创建新的重载方法.


kgi*_*kis 8

不,Java不支持C++等默认参数.您需要定义一个不同的方法:

public int doSomething()
{
   return doSomething(value1, value2);
}
Run Code Online (Sandbox Code Playgroud)