this keyword in Java

Use this in ordinary methods

  1. In the method of the class, we can use the this. property or this. method to call the current object property or method. However, in general, we choose to omit this..
  2. In special cases, if the formal parameter of the method and the attribute of the class have the same name, we must explicitly use the this. attribute to distinguish the attribute from the formal parameter.
   // The age variable in the formal parameter list is the same as the property name of the Person class. In order to distinguish, use this to call the property
   // Otherwise, according to the proximity principle, age = age just makes a meaningless assignment to the variable passed in, and will not change the attribute value
    public void setAge(int age) {
        // age = age;
        this.age = age;
    }

Use this in the constructor

  1. Use this in the constructor to call properties and methods

    • In the constructor of a class, we can use the "this.property" or "this.method" method to call the object property or method currently being created. However, in general, we choose to omit this..
    • In special cases, if the parameter of the constructor and the attribute of the class have the same name, we must explicitly use the this. attribute to distinguish the attribute from the formal parameter.
  2. Use this in the constructor to call the overloaded constructor

    If a class declares n constructors, at most n-1 constructors use this (formal parameter list) because at least one class must call super() implicitly or explicitly, otherwise the inheritance tree cannot go up. Traceback (the constructor of the parent class and indirect parent class cannot be called), and an error is reported when compiling.

    1. You can use this (formal parameter list) in the constructor of a class to call other overloaded constructors in this class!
    2. Explicit: The constructor cannot call its own constructor by means of this (formal parameter list)
    3. this (parameter list) must be in the first sentence of the constructor. So in a constructor of a class, at most one this (formal parameter list) can be declared
  • Example: Avoiding Ambiguity

package this_demo;

public class User {
    int id;
    String name;
    String pwd;

    public User() {
    }

    public User(int id, String name) {
        System.out.println("Initializing the created object:" + this);
        //Without writing this, it is impossible to distinguish between local variable id and member variable id
        this.id = id;
        this.name = name;
    }

    public void login() {
        // The effect is the same without writing this
        // In fact, instance methods implicitly pass this as a formal parameter to the method by default.
        System.out.println(this.name + ",To log in!");
    }

    public static void main(String[] args) {
        User u3 = new User(101, "Zhang San");
        System.out.println("Print three objects:" + u3);
        u3.login();
    }

}

  • memory map

  • Example: Using this() to call an overloaded constructor

package this_demo;

public class Person {
    int age, sex, grade;

    /**
     * No-argument constructor
     */
    Person() {
        System.out.println("about to initialize an object");
    }

    /**
     * Constructed with parameters 1
     *
     * @param age
     * @param sex
     * @param grade
     */
    Person(int age, int sex, int grade) {
        // Call the constructor with parameters, and must be on the first line!
        this(age, sex);
        this.grade = grade;
    }

    /**
     * Parametric Construct 2
     *
     * @param age
     * @param sex
     */
    Person(int age, int sex) {
        // System.out.println("hello");
        // Call the constructor with no arguments and must be on the first line! If this() is not on the first line, an error will be reported
        this();

        // These are all local variables instead of member variables, this line of code is meaningless
        age = age;

        // This distinguishes between member variables and local variables. This case accounts for most of the usage of this!
        this.age = age;
        this.sex = sex;
    }

    public static void main(String[] args) {
        // Person p1 = new Person(20, 1);
        Person p1 = new Person(20, 1, 9);
        p1.eat();
    }

    void eat() {
        // Call sing() in this class, where this can be omitted
        this.sing();
        System.out.println("Your mother called you home for dinner!");
    }

    void sing() {
        System.out.println("singing");
    }
}

Steps for Object Creation

Constructor is an important way to create Java objects. When the constructor is called through the new keyword, the constructor does return an object of the class, but this object is not completely created by the constructor.

  • Creating an object is divided into the following four steps:
    1. Allocate space in heap memory (the object already exists at this time), and perform default initialization of object properties (initialized to the default value of the corresponding type: 0 or null)
    2. Perform explicit initialization of property values
    3. Execute a non-static initializer block
    4. execute constructor
      • this() and super(): Backtracking the inheritance tree, starting from the constructor of the Object class, until the current class
      • Execute the remaining initialization statements in the constructor
    5. Returns the address of the object to the associated variable

The essence of this is "the address of the created object". Because the object has been created before the constructor is called. Therefore, this can also be used in the constructor to represent the "current object".

Summarize:  

  1. this represents the current object;

    The object that is currently operating this method is called the current object

    • In a normal method, this always points to the object on which the method is called.

      Instance methods implicitly pass this as a formal parameter to the calling method by default, so this can be used directly in the method to represent the current object

    • In a constructor, this always points to the object being initialized.

  2. this can call the properties, methods and constructors of the class

    1. In any method or constructor, if you use the member variable or member method of the current class, you can add this in front of it to enhance the readability of the program. However, usually we are used to omit this.
    2. When the form participates in the member variable with the same name, if you need to use the member variable in the method or the constructor, you must add this to indicate that the variable is a member variable of the class
    3. When using this to access properties and methods, if they are not found in this class, they will be found in the parent class
    4. this cannot be used in static methods.

Tags: Java JavaSE

Posted by phpvn.org on Sat, 15 Oct 2022 21:11:01 +0300