class Hello {
String s = "Hello";
public Hello(String s) {
System.out.println("參數 s = " + s);
System.out.println("實例變量 this.s = " + this.s);
this.s = s; // 賦值給實例變量
}
}
class Flower {
Flower(int petals) { /* ... */ }
Flower(String s) { /* ... */ }
Flower(int petals, String s) {
this(petals); // 必須放第一行,且只能調用一個
// this(s); // 錯誤:不能調用兩個
}
}
class A {
public A() { new B(this).print(); }
void print() { System.out.println("A"); }
}
class B {
A a;
B(A a) { this.a = a; }
void print() { a.print(); System.out.println("B"); }
}
class Outer {
int i = 1;
void start() {
new Thread() {
public void run() {
Outer.this.run(); // 必須用 Outer.this 區分
}
}.start();
}
void run() { System.out.println(i++); }
}
this 永遠指向**當前正在執行該代碼的對象實例**。是區分作用域、構造器鏈、對象傳遞、內部類外部引用的核心語法。