今天小編給大家分享的是java中什么時候調用this,相信很多人都不太了解,為了讓大家更加了解java調用this,給大家總結了以下內容,話不多說,一起往下看吧。
this只存在于方法內部,用來代表調用改方法的對象??梢岳斫鉃槊恳粋€方法內部都有一個局部變量叫this,每當初始化一個對象時,就把該對象的地址傳遞給了該對象每一個方法中的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();
}
}
結果為:44、在構造器中調用構造器需要使用this
一個類有許多構造函數,有時候想在一個構造函數中調用其他構造函數,以避免代碼重復,可以使用this關鍵字。

關于java中什么時候調用this的內容就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。