this关键字

对象创建的过程和this的本质

构造方法是创建 java 对象的重要途径,通过 new 关键字调用构造器时,构造器也确实返回该类的对象,但这个对象并不是完全由构造器负责创建。

创建一个对象分为如下四步:

  1. 分配对象空间,并将对象成员变量初始化为 0 或空
  2. 执行属性值的显示初始化
  3. 执行构造方法
  4. 返回对象的地址给相关的变量

this 的本质就是 “创建好的对象的地址” 由于在构造方法调用前,对象已经创建。因此,在构造方法中也可以使用 this 代表 “当前对象” 。

/**
 * 1.this的作用
 *      每创建一个对象,都会有一个this的引用变量,指向当前对象
 *      在类的内部可以使用this来访问类的成员
 *
 * 2.this的使用  this用来访问类的成员
 *      ① this.id = id; 调用成员变量   如果局部变量和成员变量同名,需要使用this来区分(this.成员变量 = 局部变量)
 *      ② this.show();  调用成员方法    this可以省略
 *      ③ this(id,name); 调用构造方法   必须是构造方法的第一条语句
 */
public class Student {
    int id;
    String name;
    int age;
    public Student(){

    }
    public Student(int id,String name){
        this.id = id;
        this.name = name;
    }
    public Student(int id,String name,int age){
//        this.id = id;
//        this.name = name;
        this(id,name);
        this.age = age;
    }
    public void show(){
        System.out.println("我的学号是:"+id+",我的名字叫做:"+name+",今年"+age+"岁了");
    }
    public void study(){
        show();
//        this.show();
        System.out.println("good good study,day day up !!");
    }

    public static void main(String[] args) {
        Student stu = new Student();
        stu.id = 1;
        stu.name = "慢慢";
        stu.age = 22;
        stu.study();

        Student stu2 = new Student(2,"某某",23);
        stu2.study();

    }

}

在这里插入图片描述
笔记学习来自某站

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值