What is the meaning of “this” in Java?

后端 未结 21 2563
走了就别回头了
走了就别回头了 2020-11-21 05:41

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if i

相关标签:
21条回答
  • 2020-11-21 05:56

    It refers to the current instance of a particular object, so you could write something like

    public Object getMe() {
        return this;
    }
    

    A common use-case of this is to prevent shadowing. Take the following example:

    public class Person {
        private final String name;
    
        public Person(String name) {
            // how would we initialize the field using parameter?
            // we can't do: name = name;
        }
    }
    

    In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

    public class Person {
        private final String name;
    
        public Person(String name) {
            this.name = name;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:58

    this refers to the current object.

    Each non-static method runs in the context of an object. So if you have a class like this:

    public class MyThisTest {
      private int a;
    
      public MyThisTest() {
        this(42); // calls the other constructor
      }
    
      public MyThisTest(int a) {
        this.a = a; // assigns the value of the parameter a to the field of the same name
      }
    
      public void frobnicate() {
        int a = 1;
    
        System.out.println(a); // refers to the local variable a
        System.out.println(this.a); // refers to the field a
        System.out.println(this); // refers to this entire object
      }
    
      public String toString() {
        return "MyThisTest a=" + a; // refers to the field a
      }
    }
    

    Then calling frobnicate() on new MyThisTest() will print

    1
    42
    MyThisTest a=42
    

    So effectively you use it for multiple things:

    • clarify that you are talking about a field, when there's also something else with the same name as a field
    • refer to the current object as a whole
    • invoke other constructors of the current class in your constructor
    0 讨论(0)
  • 2020-11-21 05:59

    I would like to share what I understood from this keyword. This keyword has 6 usages in java as follows:-

    1. It can be used to refer to the current class variable. Let us understand with a code.*

    Let's understand the problem if we don't use this keyword by the example given below:

    class Employee{  
    int id_no;  
    String name;  
    float salary;  
    Student(int id_no,String name,float salary){  
    id_no = id_no;  
    name=name;  
    salary = salary;  
    }  
    void display(){System.out.println(id_no +" "+name+" "+ salary);}  
    }  
    class TestThis1{  
    public static void main(String args[]){  
    Employee s1=new Employee(111,"ankit",5000f);  
    Employee s2=new Employee(112,"sumit",6000f);  
    s1.display();  
    s2.display();  
    }}  
    

    Output:-

    0 null 0.0
    0 null 0.0
    

    In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

    class Employee{  
    int id_no;  
    String name;  
    float salary;  
    Student(int id_no,String name,float salary){  
    this.id_no = id_no;  
    this.name=name;  
    this.salary = salary;  
    }  
    void display(){System.out.println(id_no +" "+name+" "+ salary);}  
    }  
    class TestThis1{  
    public static void main(String args[]){  
    Employee s1=new Employee(111,"ankit",5000f);  
    Employee s2=new Employee(112,"sumit",6000f);  
    s1.display();  
    s2.display();  
    }} 
    

    output:

    111 ankit 5000
    112 sumit 6000
    

    2. To invoke the current class method.

    class A{  
    void m(){System.out.println("hello Mandy");}  
    void n(){  
    System.out.println("hello Natasha");  
    //m();//same as this.m()  
    this.m();  
    }  
    }  
    class TestThis4{  
    public static void main(String args[]){  
    A a=new A();  
    a.n();  
    }}  
    

    Output:

    hello Natasha
    hello Mandy
    

    3. to invoke the current class constructor. It is used to constructor chaining.

    class A{  
    A(){System.out.println("hello ABCD");}  
    A(int x){  
    this();  
    System.out.println(x);  
    }  
    }  
    class TestThis5{  
    public static void main(String args[]){  
    A a=new A(10);  
    }}
    

    Output:

    hello ABCD
    10
    

    4. to pass as an argument in the method.

    class S2{  
      void m(S2 obj){  
      System.out.println("The method is invoked");  
      }  
      void p(){  
      m(this);  
      }  
      public static void main(String args[]){  
      S2 s1 = new S2();  
      s1.p();  
      }  
    }  
    

    Output:

    The method is invoked
    

    5. to pass as an argument in the constructor call

    class B{  
      A4 obj;  
      B(A4 obj){  
        this.obj=obj;  
      }  
      void display(){  
        System.out.println(obj.data);//using data member of A4 class  
      }  
    }  
    
    class A4{  
      int data=10;  
      A4(){  
       B b=new B(this);  
       b.display();  
      }  
      public static void main(String args[]){  
       A4 a=new A4();  
      }  
    } 
    

    Output:-

    10
    

    6. to return current class instance

    class A{  
    A getA(){  
    return this;  
    }  
    void msg(){System.out.println("Hello");}  
    }  
    class Test1{  
    public static void main(String args[]){  
    new A().getA().msg();  
    }  
    }  
    

    Output:-

    Hello
    

    Also, this keyword cannot be used without .(dot) as it's syntax is invalid.

    0 讨论(0)
  • 2020-11-21 05:59

    As everyone said, this represents the current object / current instance. I understand it this way, if its just "this" - it returns class object, in below ex: Dog if it has this.something, something is a method in that class or a variable

    class Dog {
    private String breed;
    private String name;
    
    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }
    
    public Dog getDog() {
        // return Dog type
        return this;
    }
    

    }

    0 讨论(0)
  • 2020-11-21 06:01

    To be complete, this can also be used to refer to the outer object

    class Outer {
        class Inner {
            void foo() {
                Outer o = Outer.this;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-21 06:03

    It refers to the instance on which the method is called

    class A {
    
      public boolean is(Object o) {
        return o == this;
      }
    
    }
    
    A someA = new A();
    A anotherA = new A();
    someA.is(someA); // returns true
    someA.is(anotherA); // returns false
    
    0 讨论(0)
提交回复
热议问题