java篇---this引用

this的使用

1.this.成员变量名 //访问成员变量
2.this.成员方法名() //访问成员方法

 public void setDate(Date this,int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void print(Date this){
        this.setDate(2000,1,6);
        System.out.println(this.year+"."+this.month+"."+this.day);
    }

在这里插入图片描述
3.this.() //访问本类中其他的构造方法

 class Date{
 public Date(){
        this(2022,4,8);
        System.out.println("不带参数的构造方法");
    }
    public Date(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
        System.out.println("带2个参数的构造方法");
    }
 }
 public class Demo {
    public static void main(String[] args) {
        Date date = new Date();
        date.print();
    }
}

在这里插入图片描述
this()会调用本类中合适的构造方法,且必须放在第一行!!
this()必须在构造方法中使用,而且在当前构造方法中只能调用一个

注意:

this的使用不能形成环
在这里插入图片描述
一些关于this的总结
this代表当前对象的引用

class Date{
    public int year;
    public int month;
    public int day;

    public void setDate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void print(){
        System.out.println(this.year+"."+this.month+"."+this.day);
    }
}
public class Demo {
    public static void main(String[] args) {
        Date date1 = new Date();
        date1.setDate(2008,8,8);
        date1.print();
        Date date2 = new Date();
        date2.setDate(2009,9,15);
        date2.print();
    }
}

在这里插入图片描述
在这里插入图片描述
可以看出,this代表当前对象的引用,this和date1,this和date2的地址是一样的。谁通过.操作符操作成员变量或者成员方法,谁就是当前对象。那么,在就解决了参数名和成员名冲突时,通过this就知道给哪个对象的成员变量赋值了。
当不使用this时
在这里插入图片描述

在这里插入图片描述
此时,局部变量优先,无法区别开来,出了这个代码块其生命周期结束,没有为对象的成员变量赋值。

总结

1.this代表当前对象的引用,可以区别或者防止当成员参数和成员名字相同时。
本例中this的类型是Date,即它的类型对应类类型引用,也就是说哪个对象调用就是哪个对象的引用类型
2.可以解决成员变量名和参数名冲突时,通过this知道为哪个对象的成员变量赋值
3.this只能在成员方法中使用,不能在静态方法中使用
3.this可以看作是一个隐式的参数,且是参数列表的第一个
在这里插入图片描述
4.建议在当前类中访问自己的成员变量时加上this
5.java编译器给每个“成员方法”加上了一个隐式的引用类型参数,该引用类型参数指向当前对象,在成员方法中对于成员变量的操作,由this引用去访问。在成员方法执行时,编译器自动将调用成员方法对象的引用传递给该成员方法,this负责接收
6.this不能为空

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值