Are default parameter values supported by Java? [duplicate]

孤者浪人 提交于 2021-02-18 06:01:30

问题


Possible Duplicate: Does Java support default parameter values?

Suppose I want to make default parameter value in C++, then we can express it as below.

void functionName(char *param1, int param2=2);

But if I want to make this in Java, then is it possible. Currently I am doing as below

public functionName(String param1)
{
    this(param1, 2);
}

public functionName(String param1, int param2)
{
..........
}

回答1:


It is not possible in Java,but you want you can use the Builder Pattern, which is said this Stack Overflow answer.

As described in the answer reference, the Builder Pattern lets you write code like

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

in which some fields can have default values or otherwise be optional.




回答2:


No. This feature is not supported in Java.

Does Java support default parameter values?



来源:https://stackoverflow.com/questions/13864692/are-default-parameter-values-supported-by-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!