java中this的两个作用

什么是 this 引用: java 编译器给每个 成员方法 增加了一个隐藏的引用类型参数,该引用参数指向当前对象 ( 成员方法运行 时调用该成员方法的对象 ) ,在成员方法中所有成员变量的操作,都是通过该引用去访问 。只不过所有的 操作对用户是透明的,即用户不需要来传递,编译器自动完成。

this一共有两个作用:

第一个作用:this就是一个引用,类型就是当前类。

class Person(){ this  类型就是Person}

class Cat(){this 类型就是Cat}

指向当前对象,构造器中this指向的就是当前正在构造的对象。

this.属性                 此时一定是属性的全名。

第二个作用:在一个构造方法中调用其他构造方法

package mjh.week.day5;

public class Test2 {
    Test2() {
        this(18);
        System.out.println("无参");
    }

    Test2(int a) {
        System.out.println("int");
    }

    Test2(String b) {
        System.out.println("string");
    }

    public static void main(String[] args) {
        new Test2();
    }
}
this 引用的特性
1. this 的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
2. this 只能在 " 成员方法 " 中使用
3. " 成员方法 " 中, this 只能引用当前对象,不能再引用其他对象,具有 final 属性
4. this 成员方法 第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this 负责来接收。
package mjh.week.day5;

public 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 printDate() {
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }

    public static void main(String[] args) {
        Date d = new Date();
        d.setDate(2021, 12, 28);
        d.printDate();
    }
}

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穿狼皮的小红帽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值