When should I use “this” in a class?

后端 未结 18 2372
情书的邮戳
情书的邮戳 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:09

    “This” keyword in java is used to refer current class objects.

    There are 6 uses of “this” keyword in java

    1. Accessing class level variable: mostly used if local and class level variable is same
    2. Accessing class methods : this is default behavior and can be ignored
    3. For calling other constructor of same class
    4. Using ‘this’ keyword as return value : for returning current instance from method
    5. Passing ‘this’ keyword as argument to method Passing : for passing current class instance as argument
    6. this keyword as argument to constructor : for passing current class instance as argument

    ref: https://stacktraceguru.com/java/this-keyword-in-java

提交回复
热议问题