java this keyword

走远了吗. 提交于 2019-11-28 12:42:52

The Java language specification states:

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

I.e. it always points to an object, not a class.

In Java, this always refers to an object and never to a class.

this refers to current object.

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.

in java this is refer Current object

like

public class Employee{

String name,adress;

Employee(){

 this.name="employee";
 this.address="address";

}

}

In java 'this' is a keyword, basically used to refer to the current object. In the following example the setter methods are using 'this' to set the values of name and age of current object.

public class Person {

  String name;
  int age;

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public static void main(String[] args) {
    Person p = new Person();
    p.setName("Rishi");
    p.setAge(23);
    System.out.println(p.getName() + " is " + p.getAge() + " years old");
  }
}

From the official documentation (found here):

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.

What this means is that inside the code of any class, when you write this, you specify the fact that you are referring to the current object.

As a side note, you cannot use this with static fields or methods because they do not belong to any specific object (instance of the class).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!