温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中调用this

发布时间:2020-05-07 11:54:41 来源:亿速云 阅读:725 作者:Leah 栏目:编程语言

今天小编给大家分享的是java中什么时候调用this,相信很多人都不太了解,为了让大家更加了解java调用this,给大家总结了以下内容,话不多说,一起往下看吧。

this只存在于方法内部,用来代表调用改方法的对象。可以理解为每一个方法内部都有一个局部变量叫this,每当初始化一个对象时,就把该对象的地址传递给了该对象每一个方法中的this变量,从而可以在方法内部使用这个的对象。

java中调用this

java中什么时候用this?

1、当局部变量和成员变量重名的时候,在方法中使用this表示成员变量以示区分

实例:

class Demo{
    String str = "这是成员变量";
    void fun(String str){
        System.out.println(str);
        System.out.println(this.str);
        this.str = str;
        System.out.println(this.str);
    }
}
public class This{
    public static void main(String args[]){
        Demo demo = new Demo();
        demo.fun("这是局部变量");
    }
}

2、this关键字把当前对象传递给其他方法

实例:

class Person{
    public void eat(Apple apple){
        Apple peeled = apple.getPeeled();
        System.out.println("Yummy");
    }
}
class Peeler{
    static Apple peel(Apple apple){
        //....remove peel
        return apple;
    }
}
class Apple{
    Apple getPeeled(){
        return Peeler.peel(this);
    }
}
public class This{
    public static void main(String args[]){
        new Person().eat(new Apple());
    }
}

3、当需要返回当前对象的引用时,就常常在方法写return this

这种做法的好处是:当你使用一个对象调用该方法,该方法返回的是经过修改后的对象,且又能使用该对象做其他的操作。因此很容易对一个对象进行多次操作。

public class This{
    int i = 0;
    This increment(){
        i += 2;
        return this;
    }
    void print(){
        System.out.println("i = " + i);
    }
    public static void main(String args[]){
        This x = new This();
        x.increment().increment().print();
    }
}
结果为:4

4、在构造器中调用构造器需要使用this

一个类有许多构造函数,有时候想在一个构造函数中调用其他构造函数,以避免代码重复,可以使用this关键字。

java中调用this

关于java中什么时候调用this的内容就分享到这里了,当然并不止以上和大家分析的办法,不过小编可以保证其准确性是绝对没问题的。希望以上内容可以对大家有一定的参考价值,可以学以致用。如果喜欢本篇文章,不妨把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI