how to set default method argument values?

This question already has an answer here:

  • Does Java support default parameter values? 19 answers

  • You can accomplish this via method overloading.

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

    By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.


    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.


    No. Java doesn't support default parameters like C++. You need to define a different method:

    public int doSomething()
    {
       return doSomething(value1, value2);
    }
    
    链接地址: http://www.djcxy.com/p/20862.html

    上一篇: 是否有可能在String中声明Java中的默认参数?

    下一篇: 如何设置默认方法参数值?