- this關鍵字只能在方法內部使用,表示對“調用方法的那個對象”的引用。
- 只要當需要明確指出對當前對象的引用時,才需要使用this關鍵字。例如,當需要返回對當前對象的引用時,就常常在return語句中這樣寫:
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x= new Leaf();
x.increment().increment().increment().print();
}
}
由於increment()通過this關鍵字返回了當前對象的引用,所以很容易在一條語句裏對同一個對象執行多次操作。
另外,this關鍵字對於將當前對象傳遞給其他方法也很有用
class Peeler {
static Apple peel(Apple apple) {
//... remove peel
return apple; //Peeled
}
}
class Apple {
Apple getPeeled() { return Peeler.peel(this); }
}
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("oishi");
}
}
public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}
- 在構造器中調用構造器
有時候想在一個構造器中調用另一個構造器,以避免重複代碼。可用this做到
public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petal) {
petalCount = petal;
print("Constructor with int arg only, petalCount=" + petalCount);
}
Flower(String s) {
print("Contructor with String arg only, s = " + s);
this.s = s;
}
Flower(String s, int petal) {
this(petal);
this.s = s;
print("String & int args");
}
Flower() {
this("hi", 47);
print("default constructor (no args)");
}
void printPetalCount() {
print("petalCount = " + petalCount + " s = " + s);
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
/* Output:
Constructor with int arg only, petalCount = 47
String & int args
default constructor(no args)
petalCount = 47 s = hi
*/
說明:1)用this可以調用一個構造器,但不能調用兩個。
2)必須將構造器調用置於最起始處,否則編譯器會報錯
3)除構造器之外,編譯器禁止在其他任何方法中調用構造器