1. This pointer and its two uses

The this pointer is a system implicit pointer that is automatically appended to the argument list of non-static member methods. When an object calls the non-static member method, this automatically points to the object, so the object’s members can be accessed through this inside the function.

There are two uses of the this pointer:

  • In normal methods, the this pointer points to the caller of the method, that is, the object that called the method this time;
  • In the constructor, the this pointer represents the object created by the method this time;

Examples of both usages are as follows:

/ * * *@briefTest program * for two uses of the this pointer@author  mculover666
 * @date2019/4/28 * /
class A
{
    private int i;

    public A(int i)
    {
        /* The first use of this pointer is to point to the object being created */
        this.i = i;
    }
    
    public void show(a)
    {
        /* The system automatically adds this pointer to the show method to point to the caller of the method */
        //1. We can use I directly, and call this by default;
        //2. We can use this. I to display the call to this pointer;
        System.out.println("i = "+i); }}class TestThis
{
    public static void main(String[] args) 
    {
        A aa1 = new A(10);
        A aa2 = new A(20);

        /* The second use of the this pointer refers to the object on which the method was called */aa1.show(); aa2.show(); }}Copy the code

The running results are as follows:



To receive more exciting articles and resources, please subscribe to my wechat official account: “McUlover666”.