- 相關(guān)推薦
java之this關(guān)鍵字用法事例解析
java之this關(guān)鍵字用法事例解析
一、this使用范圍
1、在類的方法定義中使用的`this關(guān)鍵字代表調(diào)用該方法對象的引用。
2、當(dāng)必須指出當(dāng)前使用方法的對象是誰時,要使用關(guān)鍵字this。
3、有時使用this可以處理方法中成員變量和參數(shù)重名的情況。
4、this可以看做是一個變量,它的值是當(dāng)前對象的引用。
注:this一般出現(xiàn)在方法中,當(dāng)方法沒有被調(diào)用時。并不知道this指向那個具體的對象。
當(dāng)某個對象調(diào)用有this的方法時,this就指向調(diào)用這個方法的對象。
二、程序代碼如下:
public class TestThis{ private int i; public TestThis(int i){ this.i = i; } private TestThis increment(){ i += 1; return this; } public static void main (String[] args){ TestThis mTestThis = new TestThis(100); System.out.println(mTestThis.increment().increment().i); }}
輸出結(jié)果如下圖所示:
【java之this關(guān)鍵字用法事例解析】相關(guān)文章:
Java中synchronized關(guān)鍵字的用法07-23
Java關(guān)鍵字及注釋08-12
深入Java關(guān)鍵字null06-15