When should I use “this” in a class?

后端 未结 18 2168
情书的邮戳
情书的邮戳 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 00:11

    "this" is also useful when calling one constructor from another:

    public class MyClass {
        public MyClass(String foo) {
            this(foo, null);
        }
        public MyClass(String foo, String bar) {
            ...
        }
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 00:14

    The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:

    public class Outer {
      protected int a;
    
      public class Inner {
        protected int a;
    
        public int foo(){
          return Outer.this.a;
        }
    
        public Outer getOuter(){
          return Outer.this;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 00:15

    The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

    Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

    public class Foo
    {
        private String name;
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Case 2: Using this as an argument passed to another object.

    public class Foo
    {
        public String useBarMethod() {
            Bar theBar = new Bar();
            return theBar.barMethod(this);
        }
    
        public String getName() {
            return "Foo";
        }
    }
    
    public class Bar
    {
        public void barMethod(Foo obj) {
            obj.getName();
        }
    }
    

    Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.

    class Foo
    {
        public Foo() {
            this("Some default value for bar");
    
            //optional other lines
        }
    
        public Foo(String bar) {
            // Do something with bar
        }
    }
    

    I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

    0 讨论(0)
提交回复
热议问题