this引用

为什么会出现this引用?

class Date {
    public int year;
    public int month;
    public int day;
    public void setDay(int y, int m, int d) {
        year = y;
        month = m;
        day = d;
    }
    public void printDate() {
        System.out.println(year + "/" + month + "/" + day);
    }
}
public class Test {
        public static void main(String[] args) {
            //构造三个日期类型的对象d1,d2,d3
            Date d1 = new Date();
            Date d2 = new Date();
            Date d3 = new Date();
            
            //对d1,d2,d3的日期设置
            d1.setDay(2025,1,12);
            d2.setDay(2025,1,13);
            d3.setDay(2025,1,14);
            
            //打印日期中的内容
            d1.printDate();
            d2.printDate();
            d3.printDate();
        }
    }

以上代码定义了一个日期类,然后main方法中创建类三个对象,并通过Date类中的成员方法对对象进行设置和打印。

但是有两个问题

1.形参名与成员变量名相同

public void setDay(int year, int month, int day) {
        year = year;
        month = month;
        day = day;
    }

函数体内到底是谁给谁在赋值,是成员变量给成员变量,还是参数给成员变量? 

2.d1,d2,d3都在调用setDate和printDate函数,但这两个函数都没有任何关于对象的说明       我不知道这两个函数打印的是哪个对象的数据

就是说在成员函数没有真正执行的时候,函数体(setday和printdate)并没有关于任何对象的说明,我不知道他是怎么知道要设置的是d1,d2还是d3

故此,就引入了this引用(什么是this引用)

this引用指向当前对象,在成员方法中所有成员变量的操作,都是通过该引用去访问

还是对前面的例子进行修改

class Date {
    public int year;
    public int month;
    public int day;
    public void setDay(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void printDate() {
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }
}

this引用的都是调用成员方法的对象 

也就是说它引用的都是同一个地址,都是从一开始就调用的成员方法的对象,后面再去调用时,都是这一个物理内存的地址。


this引用的特性

  1. this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
  2. this只在成员方法中使用
  3. 在成员方法中,this只能引用当前对象
  4. this是成员方法第一个隐藏的参数,其实它就是本来有的,比如我们可以拿上面的例子来说

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值