【后端开辟】java中什么时候用this?

【后端开辟】java中什么时候用this?,第1张

this只存在于要领内部,用来代表挪用改要领的对象。


能够理解为每个要领内部都有一个局部变量叫this,每当初始化一个对象时,就把该对象的地点传递给了该对象每个要领中的this变量,从而能够在要领内部运用这个的对象。


【后端开辟】java中什么时候用this?,第2张

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?,第3张

引荐教程:Java教程

以上就是java中什么时刻用this?的细致内容,更多请关注ki4网别的相干文章!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/552919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2019-11-18
下一篇 2019-11-18

发表评论

登录后才能评论

评论列表(0条)

保存