Evg*_*nov -3 java setter return this void
Class Player {
Player setName(String name){
this.name = name;
return this;
// or
void setName(String name){
this.name = name;
}}
Run Code Online (Sandbox Code Playgroud)
你好.如果我使用"void"或"return this"语句使用该方法有什么区别?为什么"返回此"语句存在,如果它也一样?
为什么"返回此"语句存在,如果它也一样?
他们不会远程做同样的事情.
void方法没有返回值.这意味着您无法使用返回值(例如,您无法将其分配给变量).
具有返回值的方法具有返回值.在您提到的特定情况下return this,它返回对该方法被调用的对象的引用,因此您可以(可能)使用该引用 - 通过将其分配给变量,通过调用其上的另一个方法等.这对于流畅的界面(允许你进行大量链接的界面)非常有用:
theObject.doThis().thenDoThat().thenDoSomethingElse();
Run Code Online (Sandbox Code Playgroud)
如果是这样的话void,你必须这样写:
theObject.doThis();
theObject.thenDoThat();
theObject.thenDoSomethingElse();
Run Code Online (Sandbox Code Playgroud)
可能这个1中最着名的例子是对象构造的Builder模式,因为它意味着你不需要变量:
Thingy t = new ThingyBuilder()
.withFoo("foo")
.withBar("bar")
.withBaz("baz")
.build();
Run Code Online (Sandbox Code Playgroud)
1最着名的外部Web开发圈,即; 在 Web开发圈内,最着名的例子是jQuery的API:$("div").css("color", "green").text("Good");
| 归档时间: |
|
| 查看次数: |
826 次 |
| 最近记录: |