天天看點

this關鍵字表示目前對象

this表示目前對象

在一個類之中肯定會産生諾幹個對象,那麼程式類在分辨的時候不會記住具體有多少個對象産生了,它唯一可能知道的目前操作本類的對象是哪一個。

範例:觀察目前對象 

class Person{
public  void fun() {
	System.out.println("【fun方法】"+this);
	}}

public class StringDemo {
public static void main(String args[]) {
Person p1=new Person();
System.out.println("【Main方法】"+p1);
p1.fun();//由p1這個對象調用了fun()方法(this=p1)
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Person p2=new Person();
p2.fun();
}
}	
           

//結果

【Main方法】[email protected]

【fun方法】[email protected]

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

【fun方法】[email protected]

在整體的操作過程之中,this定義沒有變,

隻要有某一個對象調用了本類中的方法,那麼這個this就表示目前執行的對象。

繼續閱讀