When should I use “this” in a class?

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

    With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

    public class Window {
    
      private Window parent;
    
      public Window (Window parent) {
        this.parent = parent;
      }
    
      public void addSubWindow() {
        Window child = new Window(this);
        list.add(child);
      }
    
      public void printInfo() {
        if (parent == null) {
          System.out.println("root");
        } else {
          System.out.println("child");
        }
      }
    
    }
    

    I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

提交回复
热议问题