我们那些年对 this 的误解

什么是 this ,这个问题也许经常会有人问到。
很多人的回答是: this代表当前对象
那么这个回答对不对呢,我们往下走:

首先我们得知道一个对象的产生分为两步:
1、为对象分配内存(引用)
2、调用合适的构造方法

那么可能又有人要问了,什么是构造方法:
构造方法: 没有返回类型 ,且与类名一样

话不多说,直接上代码:

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");
   }
}

在这里插入图片描述
上面我们说过,构造方法完成后,一个对象才被创建出来,也就是图上显示的
但是我们又看到 this 出现在了构造方法里 ,此时对象还没有被创建出来, this 怎么能代表当前对象呢 ,所以 this 并不能代表当前对象!!!

那么 this 是啥?
this 其实代表的是当前对象的引用

this 的使用:
1、this.成员变量(成员变量一定是普通的成员变量而不是静态的成员变量)
2、this();构造方法
3、this.成员方法
this 调用必须放在第一行

猜你喜欢

转载自blog.csdn.net/qq_45658339/article/details/108900917