Using “this” with methods (in Java)

前端 未结 7 1992
终归单人心
终归单人心 2020-12-08 16:12

what about using \"this\" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?

The only situation I have encountered is

7条回答
  •  没有蜡笔的小新
    2020-12-08 16:57

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html

    You absolutely need this if your method needs to return the object's instance.

    public class StringBuildable {
        public StringBuildable append(String text) {
            // Code to insert the string -- previously this.internalAppend(text);
            return this;
        }
    }
    

    This allows you to chain methods together in the following fashion:

    String string = new StringBuildable()
        .append("hello")
        .append(' ')
        .append.("World")
        .toString()
    ;
    

提交回复
热议问题