Java 是否支持默认参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13864692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are default parameter values supported by Java?
提问by Bhavik Ambani
Possible Duplicate:Does Java support default parameter values?
可能的重复:Java 是否支持默认参数值?
Suppose I want to make default parameter value in C++, then we can express it as below.
假设我想在 C++ 中设置默认参数值,那么我们可以如下表示。
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
但是如果我想用 Java 来做这个,那么有可能吗。目前我正在做如下
public functionName(String param1)
{
this(param1, 2);
}
public functionName(String param1, int param2)
{
..........
}
回答by Bhavik Ambani
It is not possible in Java
,but you want you can use the Builder Pattern, which is said this Stack Overflow answer.
这是不可能的Java
,但你希望你可以使用Builder Pattern,这就是 Stack Overflow 的答案。
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.
其中某些字段可以具有默认值或以其他方式可选。