【Java学习笔记】this关键字

this 关键字

在堆空间内存分配时还会给每个对象分配 this

this 的本质:就是指向当前对象

使用细节

  • this 不能在类定义的外部使用,只能在类定义的方法中使用

  • this 关键字可以用来访问本类的属性、方法、构造器

  • this 用于区分当前类的属性局部变量

  • 访问成员方法的语法:this.方法名(参数列表)

  • 访问构造器语法:this(参数列表); 注意只能在构造器中使用(即只能在构造器中访问另外一个构造器,必须放在第一条语句

代码示例

public class this关键字 {
    public static void main(String[] args) {
        thiss th = new thiss(18, "jackson");
        System.out.println("th.age:" + th.age);
        System.out.println("th.name:" + th.name);
    }
}

class thiss {
    int age;
    String name;

    public thiss(int age, String name) {
        this.age = age;
        this.name = name;
    }
}
//输出
th.age:18
th.name:jackson

this.name , this.age指向的都是对象中的属性,而不是局部变量,实现了局部变量和全局变量同名但是作用域不同


练习题

定义 Person 类,里面有 name、age 属性,并提供 compareTo 比较方法,用于判断是否和另一个人相等,提供测试类 TestPerson,用于测试,名字和年龄完全一样,就返回 true,否则返回 false

public class homework2 {
    public static void main(String[] args){
        person p = new person(18,"jackson");
        person testperson = new person(18,"jackson");
        System.out.print(p.compareto(testperson));
    }
}
class person{
    int age;
    String name;
    public person(int age,String name){
        this.name =  name;
        this.age = age;
    }
    public boolean compareto(person p){
        return this.name.equals(p.name) && this.age == p.age;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

jackson凌

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

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

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

打赏作者

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

抵扣说明:

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

余额充值