1. 當成員變量和局部變量重名時,在方法中使用this時,表示的是該方法所在類中的成員變量。(this是當前對象本身)函數
如:public class Hello {測試
String s = "Hello";this
public Hello(String s) {對象
System.out.println("s = " + s);事件
System.out.println("1 -> this.s = " + this.s);開發
this.s = s;//把參數值賦給成員變量,成員變量的值改變it
System.out.println("2 -> this.s = " + this.s);io
}class
public static void main(String[] args) {thread
Hello x = new Hello("HelloWorld!");
System.out.println("s=" + x.s);//驗證成員變量值的改變
}
}
結果爲:s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
s=HelloWorld!
在這個例子中,構造函數Hello中,參數s與類Hello的成員變量s同名,這時若是直接對s進行操做則是對參數s進行操做。若要對類Hello的成員變量s進行操做就應該用this進行引用。運行結果的第一行就是直接對構造函數中傳遞過來的參數s進行打印結果; 第二行是對成員變量s的打印;第三行是先對成員變量s賦傳過來的參數s值後再打印,因此結果是HelloWorld!而第四行是主函數中直接打印類中的成員變量的值,也能夠驗證成員變量值的改變。
2.把本身看成參數傳遞時,也能夠用this.(this做當前參數進行傳遞)
class A {
public A() {
new B(this).print();// 調用B的方法
}
public void print() {
System.out.println("HelloAA from A!");
}
}
class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();//調用A的方法
System.out.println("HelloAB from B!");
}
}
public class HelloA {
public static void main(String[] args) {
A aaa = new A();
aaa.print();
B bbb = new B(aaa);
bbb.print();
}
}
結果爲:HelloAA from A!
HelloAB from B!
HelloAA from A!
HelloAA from A!
HelloAB from B!
在這個例子中,對象A的構造函數中,用new B(this)把對象A本身做爲參數傳遞給了對象B的構造函數。
3. 有時候,咱們會用到一些內部類和匿名類,如事件處理。當在匿名類中用this時,這個this則指的是匿名類或內部類自己。這時若是咱們要使用外部類的方法和變量的話,則應該加上外部類的類名。如:
public class HelloB {
int i = 1;
public HelloB() {
Thread thread = new Thread() {
public void run() {
for (int j=0;j<20;j++) {
HelloB.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 HelloB();
}
}
在上面這個例子中, thread 是一個匿名類對象,在它的定義中,它的 run 函數裏用到了外部類的 run 函數。這時因爲函數同名,直接調用就不行了。這時有兩種辦法,一種就是把外部的 run 函數換一個名字,但這種辦法對於一個開發到中途的應用來講是不可取的。那麼就能夠用這個例子中的辦法用外部類的類名加上 this 引用來講明要調用的是外部類的方法 run。
4. 在構造函數中,經過this能夠調用同一類中別的構造函數。如:
public class ThisTest {
ThisTest(String str) {
System.out.println(str);
}
ThisTest() {
this("this測試成功!");
}
public static void main(String[] args) {
ThisTest thistest = new ThisTest();
}
}
爲了更確切的說明this用法,另一個例子爲:
public class ThisTest {
private int age;
private String str;
ThisTest(String str) {
this.str=str;
System.out.println(str);
}
ThisTest(String str,int age) {
this(str);
this.age=age;
System.out.println(age);
}
public static void main(String[] args) {
ThisTest thistest = new ThisTest("this測試成功",25);
}
}
結果爲:this測試成功
25
值得注意的是:
1:在構造調用另外一個構造函數,調用動做必須置於最起始的位置。
2:不能在構造函數之外的任何函數內調用構造函數。
3:在一個構造函數內只能調用一個構造函數。
5.this同時傳遞多個參數。
public class TestClass {
int x;
int y;
static void showtest(TestClass tc) {//實例化對象
System.out.println(tc.x + " " + tc.y);
}
void seeit() {
showtest(this);
}
public static void main(String[] args) {
TestClass p = new TestClass();
p.x = 9;
p.y = 10;
p.seeit();
}
}
結果爲:9 10
代碼中的showtest(this),這裏的this就是把當前實例化的p傳給了showtest()方法,從而就運行了。