When should I use “this” in a class?

后端 未结 18 2186
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  花落未央
    2020-11-22 00:11

    @William Brendel answer provided three different use cases in nice way.

    Use case 1:

    Offical java documentation page on this provides same use-cases.

    Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

    It covers two examples :

    Using this with a Field and Using this with a Constructor

    Use case 2:

    Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.

    synchronized(this){
        // Do some thing. 
    }
    

    Use case 3:

    Implementation of Builder pattern depends on use of this to return the modified object.

    Refer to this post

    Keeping builder in separate class (fluent interface)

提交回复
热议问题