美文网首页
java中this关键字什么时候使用

java中this关键字什么时候使用

作者: 小人物不说大话 | 来源:发表于2020-03-14 17:49 被阅读0次

java中this关键字什么时候使用

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

实例:

classDemo{

    String str = "这是成员变量";

    void fun(String str){

        System.out.println(str);

        System.out.println(this.str);

        this.str = str;

        System.out.println(this.str);

    }

}

publicclassThis{

    publicstaticvoid main(String args[]){

        Demo demo = newDemo();

        demo.fun("这是局部变量");

    }

}

学习视频分享:java视频教程

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

实例:

classPerson{

    publicvoid eat(Apple apple){

        Apple peeled = apple.getPeeled();

        System.out.println("Yummy");

    }

}

classPeeler{

    staticApple peel(Apple apple){

        //....remove peel

        returnapple;

    }

}

classApple{

    Apple getPeeled(){

        returnPeeler.peel(this);

    }

}

publicclassThis{

    publicstaticvoid main(String args[]){

        newPerson().eat(newApple());

    }

}

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

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

publicclassThis{

    int i = 0;

    This increment(){

        i += 2;

        returnthis;

    }

    void print(){

        System.out.println("i = "+ i);

    }

    publicstaticvoid main(String args[]){

        This x = newThis();

        x.increment().increment().print();

    }

}

结果为:4

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

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

推荐教程:java快速入门

相关文章

网友评论

      本文标题:java中this关键字什么时候使用

      本文链接:https://www.haomeiwen.com/subject/xxvgshtx.html