Home  >  Article  >  Java  >  The role of this keyword in java

The role of this keyword in java

下次还敢
下次还敢Original
2024-05-01 17:30:23475browse

The this keyword in Java refers to the current object instance. It is used to access member variables and methods, call other constructors from the constructor, return the current object reference, and other occasions.

The role of this keyword in java

The role of this keyword in Java

In Java, the this keyword is a reference that points to The current object instance. It is mainly used for the following purposes:

Access the member variables and methods of the current object:

  • The instance variables of the current object can be accessed through the this. variable name.
  • You can call the method of the current object through this.method name().

Example:

<code class="java">class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }
}</code>

Call other constructors from the constructor:

  • this( parameter list) can call another constructor from the current constructor.
  • This is usually used to overload the constructor to initialize the object based on different parameters.

Example:

<code class="java">class Employee {
    private String name;
    private int salary;

    public Employee(String name) {
        this(name, 0);
    }

    public Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }
}</code>

Returns the current object reference:

  • this can be used as a method Return value to return a reference to the current object instance.
  • This is useful in certain situations, such as callback functions or chained methods.

Example:

<code class="java">class StringBuilder {
    private String str;

    public StringBuilder append(String s) {
        str += s;
        return this; // 返回当前 StringBuilder 对象引用
    }
}</code>

Other uses:

  • This can be used with superclass references , to access superclass methods and variables.
  • This can be used to resolve references to external variables in anonymous inner classes and lambda expressions.

The above is the detailed content of The role of this keyword in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn