我遇到了一些具有以下结构的Java代码:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

我知道,在C++中,我可以为参数指定默认值。例如:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Java是否支持这种语法?这两步语法是可取的,有什么原因吗?


当前回答

一个想法是使用字符串。。。参数

public class Sample {
   void demoMethod(String... args) {
      for (String arg : args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ) {
      new Sample().demoMethod("ram", "rahim", "robert");
      new Sample().demoMethod("krishna", "kasyap");
      new Sample().demoMethod();
   }
}

输出

ram
rahim
robert
krishna
kasyap

从…起https://www.tutorialspoint.com/Does-Java-support-default-parameter-values-for-a-method

其他回答

类似的方法https://stackoverflow.com/a/13864910/2323964在Java8中工作的是使用带有默认getter的接口。这将使空白更加冗长,但可以模拟,并且非常适合在有大量实例需要注意参数的情况下使用。

public class Foo() {
    public interface Parameters {
        String getRequired();
        default int getOptionalInt(){ return 23; }
        default String getOptionalString(){ return "Skidoo"; }
    }

    public Foo(Parameters parameters){
        //...
    }

    public static void baz() {
        final Foo foo = new Foo(new Person() {
            @Override public String getRequired(){ return "blahblahblah"; }
            @Override public int getOptionalInt(){ return 43; }
        });
    }
}

尝试此解决方案:

public int getScore(int score, Integer... bonus)
{
    if(bonus.length > 0)
    {
        return score + bonus[0];
    }

    return score;
}

我可能在这里说明了显而易见的情况,但为什么不自己实现“默认”参数呢?

public class Foo() {
        public void func(String s){
                func(s, true);
        }
        public void func(String s, boolean b){
                //your code here
        }
}

对于默认值,您可以使用

func("my string");

如果您不想使用默认值,可以使用

func("my string", false);

遗憾的是,没有。

没有,但您可以使用生成器模式,如堆栈溢出答案中所述。

如链接答案中所述,生成器模式允许您编写如下代码

Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
                 .name("Spicoli")
                 .age(16)
                 .motto("Aloha, Mr Hand")
                 .buildStudent();

其中某些字段可以具有默认值或可选。