我遇到了一些具有以下结构的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是否支持这种语法?这两步语法是可取的,有什么原因吗?


当前回答

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

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

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

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

其他回答

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

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);

类似于方法的构造函数

static void popuping() {
    popuping("message", "title");
}
static void popuping(String message) {
    popuping(message, "title");
}
static void popuping(String message, String title){
    JOptionPane.showMessageDialog(null, message,
            title, JOptionPane.INFORMATION_MESSAGE);
}

遗憾的是,没有。

您可以使用以下选项-

public void mop(Integer x) {
  // Define default values
        x = x == null ? 200 : x;
}

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

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

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

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