談談 Java 中 this 的使用方法
1. this是指當前對象自己。
當在一個類中要明確指出使用對象自己的的變量或函數(shù)時就應該加上this引用。如下面這個例子中:
public class A {
String s = "Hello";
public A(String s) {
System.out.println("s = " + s);
System.out.println("1 -> this.s = " + this.s);
this.s = s;
System.out.println("2 -> this.s = " + this.s);
}
public static void main(String[] args) {
new A("HelloWorld!");
}
}
運行結果:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
在這個例子中,構造函數(shù)A中,參數(shù)s與類A的變量s同名,這時如果直接對s進行操作則是對參數(shù)s進行操作。若要對類A的變量s進行操作就應該用this進行引用。運行結果的第一行就是直接對參數(shù)s進行打印結果;后面兩行分別是對對象A的變量s進行操作前后的打印結果。
2. 把this作為參數(shù)傳遞
當你要把自己作為參數(shù)傳遞給別的對象時,也可以用this。如:
public class A {
public A() {
new B(this).print();
}
public void print() {
System.out.println("Hello from A!");
}
}
public class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}
}
運行結果:
Hello from A!
Hello from B!
在這個例子中,對象A的構造函數(shù)中,用new B(this)把對象A自己作為參數(shù)傳遞給了對象B的構造函數(shù)。
3. 注意匿名類和內部類中的this。
有時候,我們會用到一些內部類和匿名類。當在匿名類中用this時,這個this則指的是匿名類或內部類本身。這時如果我們要使用外部類的方法和變量的話,則應該加上外部類的類名。如下面這個例子:
public class A {
int i = 1;
public A() {
Thread thread = new Thread() {
public void run() {
for(;;) {
A.this.run();
try {
sleep(1000);
} catch(InterruptedException ie) {
}
}
}
};
thread.start();
}
public void run() {
System.out.println("i = " + i);
i++;
}
public static void main(String[] args) throws Exception {
new A();
}
}
在上面這個例子中, thread 是一個匿名類對象,在它的定義中,它的 run 函數(shù)里用到了外部類的 run 函數(shù)。這時由于函數(shù)同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的 run 函數(shù)換一個名字,但這種辦法對于一個開發(fā)到中途的應用來說是不可取的。那么就可以用這個例子中的辦法用外部類的類名加上 this 引用來說明要調用的是外部類的方法 run。
相關文章
RocketMQ線程池創(chuàng)建實現(xiàn)原理詳解
這篇文章主要為大家介紹了RocketMQ線程池創(chuàng)建實現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
基于HttpServletRequest 相關常用方法的應用
本篇文章小編為大家介紹,基于HttpServletRequest 相關常用方法的應用,需要的朋友參考下2013-04-04
微信小程序與AspNetCore SignalR聊天實例代碼
這篇文章主要介紹了微信小程序與AspNetCore SignalR聊天實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
SpringCloud?Function?SpEL注入漏洞分析及環(huán)境搭建
SpringCloud 是一套分布式系統(tǒng)的解決方案,常見的還有阿里巴巴的Dubbo,F(xiàn)ass的底層實現(xiàn)就是函數(shù)式編程,SpringCloud Function 就是Spring提供的分布式函數(shù)式編程組件,下面給大家介紹下SpringCloud?Function?SpEL注入漏洞分析,感興趣的朋友一起看看吧2022-04-04
Springboot項目編譯后未能加載靜態(tài)資源文件的問題
這篇文章主要介紹了Springboot項目編譯后未能加載靜態(tài)資源文件的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08

