The use of “this” in Java

后端 未结 13 1949
-上瘾入骨i
-上瘾入骨i 2020-12-09 21:58

If I write the following class:

public class Example {

      int j;
      int k;

      public Example(int j, int k) {
           j = j;
           k = k;
          


        
13条回答
  •  情歌与酒
    2020-12-09 22:48

    this is useful when you want to return the object itself

    return this;
    

    This is useful because if a class has for example Method1() and Method2(), both returning this, you are allowed to write calls like

    object.Method1().Method2()
    

    Also inside a method it can be useful to pass the object itself to another function, during a call.

提交回复
热议问题