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");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…