this是指向本身的隱含的指針,簡單的說,哪個對象調用this所在的方法,那么this就是哪個對象。
示例代碼: TestThis_1.java
/* 問題:什么是this
* 輸出結果:
* A@4e44ac6a
*/
public class TestThis_1 {
public static void main(String[] args) {
A aa = new A();
System.out.println(aa.f()); //aa.f(), 返回aa這個對象的引用(指針)
}
}
class A {
public A f() {
return this; //返回調用f()方法的對象的A類對象的引用
}
}
this的常見用法
1. 區分同名變量
示例代碼: TestThis_2.java
/* this的常見用法1:區分同名變量
* 輸出結果:
* this. i = 1
* i = 33
*/
public class TestThis_2 {
public static void main(String[] args) {
A aa = new A(33);
}
}
class A {
public int i = 1; //這個i是成員變量
/*注意:一般不這么寫,構造函數主要是為了初始化,這么寫主要是為了便于理解*/
public A(int i) { //這個i是局部變量
System.out.printf("this. i = %d\n", this.i); //this.i指的是對象本身的成員變量i
System.out.printf("i = %d\n", i); //這里的i是局部變量i
}
}
2. 構造方法間的相互調用
示例代碼: TestThis_3.java
/* this的常見用法2: 構造方法中互相調用*/
public class TestThis_3 {
public static void main(String[] args) {
}
}
class A {
int i, j, k;
public A(int i) {
this.i = i;
}
public A(int i, int j) {
/* i = 3; error 如果不注釋掉就會報錯:用this(...)調用構造方法的時候,只能把它放在第一句
* TestThis_3.java:20: error: call to this must be first statement in constructor
* this(i);
* ^
* 1 error
*/
this(i);
this.j = j;
}
public A(int i, int j, int k) {
this(i, j);
this.k = k;
}
}
注意事項
被static修飾的方法沒有this指針。因為被static修飾的方法是公共的,不能說屬于哪個具體的對象的。
示例代碼: TestThis_4.java
/*static方法內部沒有this指針*/
public class TestThis_4 {
public static void main(String[] args) {
}
}
class A {
static A f() {
return this;
/* 出錯信息:TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
* return this;
* ^
* 1 error
*/
}
}