Java中this的四种用法

本文介绍了Java中this关键字的四种用法:1) 区分成员变量与局部变量;2) 调用成员方法;3) 互相调用构造方法;4) 直接指代对象本身。通过示例解释了this在实际编程中的应用。

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

java中this关键字主要是用在类的成员方法中,用来指代本类所指的一个对象,注意是指代一个对象,所以this不能在静态方法中使用(因为静态方法是在类加载的时候出现的,但是对象是在类加载之后的实例化出现的,可以理解为静态方法在this出现之前就已经存在,所以不能调用)。

  1. this调用成员变量
    我们现在举个例子来说明,一个箱子Box里面可以装两个球(str1和str2),现在已经有了一个足球,但是我们现在给这个箱子的属性里添加一个动作(成员方法change),可以把里面本来的球1换成指定的另外一个球。
class Box {
    String str1  = "足球";
    String str2;
    void change (String str1) {
        this.str1 = str1;  //this调用成员变量
        System.out.println("换成"+str1);
    }
}

public class Main {

    public static void main(String[] args) {
       Box box = new Box();
       System.out.println("箱子里有"+box.str1);
       box.change("篮球");
       System.out.println("箱子里有"+box.str1);
    }
}

在这里插入图片描述
这里面的this所起到的作用就是用来区分成员变量str1和局部变量str1的,this.str1指的就是成员变量

  1. this调用成员方法
    我们现在给这个Box多加一个动作,换掉里面的足球同时再放一个排球,我们已经有了换足球的动作,现在可以直接加一个放排球的,然后在main函数里面分别调用,但是我们也可以用this关键字直接在新方法里面调用成员方法
class Box {
    String str1  = "足球";
    String str2;
    void change (String str1) {
        this.str1 = str1;  //this调用成员变量
        System.out.println("换成"+str1);
    }
    void changeAndInput(String str){
        this.change(str);//this调用成员方法
        this.str2 = "排球";
    }
}

public class Main {

    public static void main(String[] args) {
        Box box = new Box();
        System.out.println("箱子里有"+box.str1);
        box.changeAndInput("篮球");
        System.out.println((box.str2 == null) ? "箱子里有"+box.str1 : "箱子里有"+box.str1+"和"+box.str2);
    }
}

在这里插入图片描述
这里面的this调用的就是刚刚说的换篮球的成员方法

  1. this用来互相调用构造方法
    比如说我们现在只有一个Box,里面什么都没有的话,我们用构造方法可以初始化Box里面的球
class Box {
    String str1;
    String str2;
    Box(String str1,String str2){
        this.str1 = str1;
        this.str2 = str2;
    }
    Box(){
        this("篮球","足球");//this调用构造函数
    }
}

public class Main {

    public static void main(String[] args) {
        Box box = new Box();
        System.out.println((box.str2 == null) ? "箱子里有"+box.str1 : "箱子里有"+box.str1+"和"+box.str2);
    }
}

在这里插入图片描述
这里面this用来调用构造函数的用法 this(参数),需要注意的是,这种用法只能在构造方法里面调用其他构造方法,同时必须在该方法的第一行使用。

  1. this直接指代本身对象
    这个地方我就不举例子了,应该很难遇到,只是我在看hashMap的源码中间看到的发出来大家一起瞅瞅就好~
 public final boolean equals(Object o) {
            if (o == this) 
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }

在代码第二行可以看到直接用this指代了本类的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值