Java中关键字 this 引用

Java中关键字 : this 引用

为什么要有this引用

举个代码例子

public class Date {
    public int year = 1008;
    public int month = 6;
    public int day = 11;
    //不加this
    public void setDay1(int year, int month, int day){
        year = year;
        month = month;
        day = day;
    }
    //加上this
    public void setDay2(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate1(){
        System.out.println(year + "/" + month + "/" + day);
    }
    public void printDate2(){
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }

    public static void main(String[] args) {
        // 构造两个日期类型的对象 d1 d2
        Date d1 = new Date();
        d1.setDay1(2022,5,11);
        d1.printDate1();
        Date d2 = new Date();
        d2.setDay2(2022,5,11);
        d2.printDate2();
    }
}

在这里插入图片描述

在这里插入图片描述

所以我们可以得出: this关键字指向的是当前对象的引用

this.属性名称

**指的是访问类中的成员变量,用来区分成员变量和局部变量(重名问题)**

this引用的特性

  1. this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
  2. this只能在"成员方法"中使用,不能在静态方法中使用
  3. 在"成员方法"中,this只能引用当前对象,不能再引用其他对象

this() 调用当前对象的构造方法

​ 其中()里面可以有参数,如果有参数就是调用指定的有参构造.

注意事项:

  1. this.方法名称 -> 表达的意思是用来访问本类的成员方法.
  2. this() 不能使用在普通方法中 只能写在构造方法中
  3. this()必须是构造方法中第一条语句
  4. this() 不能形成环
public class Date {
    public int year;
    public int month;
    public int day;
    public Date() {
        this(2022,05,11);
        System.out.println("不带参数构造方法!");
    }
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void printDate(){
        System.out.println(year + "/" + month + "/" + day);
    }
    public static void main(String[] args) {
        // 构造两个日期类型的对象 d1 d2
        Date d1 = new Date();
        d1.printDate();
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

注意

1. this可以使用在实例方法中,不能使用在静态方法中。
2. this关键字大部分情况下可以省略,什么时候不能省略呢?
在实例方法中,或者构造方法中,为了区分局部变量和实例变量,这种情况下:this. 是不能省略的。

this.方法名

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值