java中this这个概念初学者非常难理解,请举例说明

本文详细介绍了Java中的this关键字使用方法,包括如何通过this关键字区分局部变量与实例变量,以及在构造函数和成员方法中如何利用this关键字进行自我引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4.this关键字(this key word)
继上一小节,(3.一个对象可能有多个参考)this是当中的一个参考!指向他自己。

class MyTestDate {
    int year;
    int month;
    MyTestDate(int year, int month, int day) {
/* 为了学习this的用法,本例中,我们故意用了两个相同的year,一个是全类作用范围的(整个类中都有效马克-to-win):int year; 另外一个是,只有本块儿才起作用的块作用范围的MyTestDate(int year, 这两个year不是一个year,如果把this.year = year; 变成 year = year,这两个year都成了块作用范围的那个year, 这样全类作用范围的那个year等于没赋值,还是0,输出结果就会变成0/0/0, if here you use year = year;month = month; result is 0/0/0, because this.year still is 0.local variable 's scope is less than the "this" variable's scope.
*/
        this.year = year;//this.year指前面类范围的变量 int year。
        this.month = month;
    }

    void setYear(int year) {
        this.year = year;

    }

    void setMonth(int month) {
        this.month = month;

    }

/*系统见到System.out.println,会自动调用toString,初学者没必要深究*/
    public String toString() {
        return "" + year + "/" + month ;
    }
}

public class Test {
    public static void main(String[] args) {
        MyTestDate date = new MyTestDate(2009, 7, 18);
        System.out.println(date);
        date.setYear(2009);
        date.setMonth(5);
        System.out.println(date);

        MyTestDate date1 = new MyTestDate(2009, 1, 1);
        System.out.println(date1);
        date1.setYear(2006);
        date1.setMonth(6);
        System.out.println(date1);

    }
}

更多请看:https://blog.youkuaiyun.com/qq_44639795/article/details/103129544

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mark_to_win

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

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

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

打赏作者

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

抵扣说明:

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

余额充值