您好,登錄后才能下訂單哦!
今天小編給大家分享的是java中什么時候調(diào)用this,相信很多人都不太了解,為了讓大家更加了解java調(diào)用this,給大家總結了以下內(nèi)容,話不多說,一起往下看吧。
this只存在于方法內(nèi)部,用來代表調(diào)用改方法的對象。可以理解為每一個方法內(nèi)部都有一個局部變量叫this,每當初始化一個對象時,就把該對象的地址傳遞給了該對象每一個方法中的this變量,從而可以在方法內(nèi)部使用這個的對象。
java中什么時候用this?
1、當局部變量和成員變量重名的時候,在方法中使用this表示成員變量以示區(qū)分
實例:
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
這種做法的好處是:當你使用一個對象調(diào)用該方法,該方法返回的是經(jīng)過修改后的對象,且又能使用該對象做其他的操作。因此很容易對一個對象進行多次操作。
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、在構造器中調(diào)用構造器需要使用this
一個類有許多構造函數(shù),有時候想在一個構造函數(shù)中調(diào)用其他構造函數(shù),以避免代碼重復,可以使用this關鍵字。
關于java中什么時候調(diào)用this的內(nèi)容就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內(nèi)容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。