1.當類的成員變量和局部變量(類中方法中的變量)重名時,使用this.s代表類中的成員變量。
舉例:
public class Hello {
String s = "Hello";
public Hello(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) {
Hello x = new Hello("HelloWorld!");
System.out.println("s=" + x.s);//驗證成員變量值的改變
}
}
2.把自己(本類的對象)當作參數傳遞時,用B(this),也可以用B(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();
}
}
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();
}
}
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();
}
}
值得注意的是:
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();
}
}