-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
可以为方法的参数设置一个默认值吗? #24
Comments
Java不支持这种特性,如果你真的有需求,你可以
|
重载这个很简单 void method(String p1, int p2, bool p3){
// ....
};
void method(String p1, int p2){
bool p3 = false;
// ...
}; 这样就相当于给p3一个默认的参数值。 但是有的时候如果参数太多,就不适合了。 |
工厂方法public class StudentBuilder
{
private String _name;
private int _age = 14; // this has a default
private String _motto = ""; // most students don't have one
public StudentBuilder() { }
public Student buildStudent()
{
return new Student(_name, _age, _motto);
}
public StudentBuilder name(String _name)
{
this._name = _name;
return this;
}
public StudentBuilder age(int _age)
{
this._age = _age;
return this;
}
public StudentBuilder motto(String _motto)
{
this._motto = _motto;
return this;
}
} Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.age(16)
.motto("Aloha, Mr Hand")
.buildStudent(); 在上面的示例中,我们没有直接 comments问: 我有个疑问,我什么我们要创建一个StudentBuilder,而不是直接这样写
答:你这种写法有两个坏处
|
Open
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
可以为方法的参数设置一个默认值吗?
The text was updated successfully, but these errors were encountered: