Our misunderstanding of this in those years

What is this , this question may often be asked.
Many people the answer is: the this is representative of the current object
then the answer is wrong with it, we go down:

First of all, we have to know that the generation of an object is divided into two steps:
1. Allocate memory (reference) for the object
2. Call the appropriate construction method

Then someone may ask again, what is a constructor: a
constructor: no return type, and the same as the class name

Not much to say, just go to the code:

class Student {
    
    
    private String name;
    public Student(String name) {
    
     //构造方法
        this.name = name;
        System.out.println("Student(String) !!!");
    }
}
public class packaging {
    
    
    public static void main(String[] args) {
    
    
        Student student = new Student("qbs");
   }
}

Insert picture description here
As we said above, after the construction method is completed, an object is created, which is shown in the figure.
But we see this appears in the construction method. At this time, the object has not been created yet. How can this represent the current Objects, so this does not represent the current object ! ! !

So what is this?
this actually represents a reference to the current object

The use of this :
1. this. member variable (the member variable must be an ordinary member variable rather than a static member variable)
2. this(); construction method
3. this. The
call of this member method must be placed in the first line

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108900917