Do you really understand the Java this keyword?

Detailed explanation of Java this keyword

this keyword

This keyword is used to represent the current object itself or an instance of the current class. All methods and properties of the object can be called through this. For example, when the member variable has the same name as the variable inside the method, what should I do if I want to call the member variable inside the method? You can only use this to solve this problem.

this keyword import

Let's look at such a case

class Person {
    private String name;
    private int age;

    public Person(String n, int a) {
        name = n;
        age = a;
    }
}

In the construction method of the Person class, we assign the initial value to the attribute through the parameters of the construction method. This is certainly no problem. However, if our construction method can directly write the attribute name, it would be better. For example, in the construction method of the Person class, the parameters are directly changed to name and age, but there is a problem according to the scope principle of variables, The constructor's name and age are local variables, not attributes. In this case, you need to introduce the this keyword!!! We need to use this keyword in the constructor to specify the attribute, which is the name of the current object and the age of the current object. As follows:

class Person {
    private String name;
    private int age;

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

In fact, if our local variable does not conflict with the attribute, we have hidden the current this at the bottom. For example, in the above example, name = n; At the bottom of the compiler is this name = n;. However, if the local variable conflicts with the attribute, you must use the this keyword, otherwise the attribute value will not change. This keyword indicates the current object itself, for example, chestnut 🌰, We instantiate two objects with the above constructor. Each object has its own name and age. This keyword plays this role and points to its own attributes (name and age).

In order to be more intuitive, when the local variables in the construction method conflict with the attributes, we instantiate the object to observe the results with and without the this keyword.

â‘  this keyword is not used

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        name = name;
        age = age;
    }

    public void info() {
        System.out.println("full name:" + name + " Age:" + age);
    }
}

public class TestDemo01 {
    public static void main(String[] args) {
        Person person = new Person("Lv Bu", 17);
        person.info();
    }
}

Operation results:

â‘¡ Use this keyword

class Person {
    private String name;
    private int age;

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

    public void info() {
        System.out.println("full name:" + name + " Age:" + age);
    }
}

public class TestDemo01 {
    public static void main(String[] args) {
        Person person = new Person("Lv Bu", 17);
        person.info();
    }
}

Operation results:

Conclusion:
This keyword is not used in â‘ , that is, there is no attribute pointing to the current object, the attribute has not been changed, and the attribute is still the default value; On the contrary, in â‘¡, the keyword this is used to point to the property of the current object, and the property is changed.

verification:
Next, we print the address of the object to verify that this keyword represents the current object itself. Because all Java programs run on the Java virtual machine, we cannot get the address of the object, but we can get the hash code value of the object by calling the HashCode() method. It is worth noting that the hash code value is not the real address of the object, But we can simply regard it as the address of the object.
We call the hashCode() method with the object in the main function and the hashCode() method with the this keyword in the constructor to observe whether the two addresses are the same.

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println(this.hashCode());
    }

}

public class TestDemo01 {
    public static void main(String[] args) {
        Person person = new Person("Lv Bu", 17);
        System.out.println(person.hashCode());
    }
}

Operation results:

The results show that the hash code values of the two are the same, so it is verified that the this keyword points to the object itself.

this keyword usage details

1.this keyword can be used to access the properties, methods and constructors of this class
2.this keyword is used to distinguish the attributes and local variables of the current class
3. Syntax of accessing member method: this Method name (parameter list)

class A {
    public void fun1() {
        System.out.println("fun1 Method called");
    }
    public void fun2() {
        this.fun1();
        System.out.println("fun2 Method called");
    }
}
public class TestDemo02 {
    public static void main(String[] args) {
        A a = new A();
        a.fun2();
    }
}

Operation results:

Through the results, it is found that fun1 method is successfully called in fun2 method. At this time, someone may ask. I also successfully called fun1 method without this keyword, because the bottom layer of the code implies the current this keyword to you.
4. Access constructor syntax: this (parameter list);
â­• Note that this (parameter list) can only be used in the constructor and placed on the first line in the constructor.

class A {
    A() {

    }

    A(int a) {
        this();
    }

}

A parameterless constructor was called in class A.

5.this cannot be used outside the class definition, but only in the methods defined by the class
The this keyword must be associated with an object, so it can only be used in class defined methods.

6.this keyword cannot be used in static methods
Static method is a class method. It exists before any instance object. xdm who knows the class loading mechanism must know that the static modified method already exists when the class is loaded, and the object appears in memory when it is created. On the other hand, static modified methods can be called directly with the class name. When class calls are used instead of objects, this cannot point to which object, so the this keyword cannot be used in static methods.

Small trial ox knife

In order to deepen the understanding of this keyword, let's finally do such a case: define a Person class with name and age attributes, and provide compareTo comparison method to judge whether it is equal to another Person. Provide TestPerson test class to test whether the name and age are exactly the same. If they are the same, return true, otherwise return false.

The code is as follows:

class Person {
    private String name;
    private int age;

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

    public boolean compareTo(Person p) {
        return this.name.equals(p.name) && this.age == p.age;
    }
}
public class TestPerson {
    public static void main(String[] args) {
        Person p1 = new Person("Lv Bu",18);
        Person p2 = new Person("Wang Zhaojun", 17);
        System.out.println(p1.compareTo(p2));
    }
}

Operation results:

Analyze compareTo method:

 public boolean compareTo(Person p) {
        return this.name.equals(p.name) && this.age == p.age;
    }

In the compareTo method, this represents the current object, that is, the name of the current object is compared with the name of the passed in object, and the age of the current object is compared with the age of the passed in object.

Keywords: Java Back-end

Added by menwn on Tue, 25 Jan 2022 07:05:52 +0200