本文實例講述了java中this關鍵字的用法,分享給大家供大家參考。具體分析如下:
一、this使用范圍
1、在類的方法定義中使用的this關鍵字代表調用該方法對象的引用。
2、當必須指出當前使用方法的對象是誰時,要使用關鍵字this。
3、有時使用this可以處理方法中成員變量和參數重名的情況。
4、this可以看做是一個變量,它的值是當前對象的引用。
注:this一般出現在方法中,當方法沒有被調用時。并不知道this指向那個具體的對象。
當某個對象調用有this的方法時,this就指向調用這個方法的對象。
二、程序代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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); } } |
輸出結果如下圖所示:
希望本文所述對大家的Java程序設計有所幫助。