Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

java - What is the difference between void method and return this

Class Player {
Player setName(String name){
this.name = name;
return this;

// or

void setName(String name){
this.name = name;
}}

Hi. What is the difference if I use the method with "void" or "return this" statement? Why the "return this" statement exists, if it does the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why the "return this" statement exists, if it does the same?

They don't remotely do the same thing.

A void method has no return value. That means you can't use the return value (for instance, you can't assign it to a variable).

A method with a return value has a return value. In the particular case you've mentioned, return this, it's returning a reference to the object that the method was called on, so you can (potentially) use that reference — by assigning it to a variable, by calling another method on it, etc. This is useful for fluent interfaces (ones that allow you to do a lot of chaining):

theObject.doThis().thenDoThat().thenDoSomethingElse();

If it were void instead, you'd have to write that like this:

theObject.doThis();
theObject.thenDoThat();
theObject.thenDoSomethingElse();

Probably the most famous example of this1 is Builder pattern of object construction, because it means you don't need a variable:

Thingy t = new ThingyBuilder()
    .withFoo("foo")
    .withBar("bar")
    .withBaz("baz")
    .build();

1 Most famous outside web development circles, that is; inside web development circles, the most famous example would be jQuery's API: $("div").css("color", "green").text("Good");


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...