[toc]
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
# this
this指的是目前的物件(參考)
**不能放在static method裡面**
## 使用this
為什麼我們在這個class裡面了, 還要用目前的物件參考?
```java=
class Point {
public int x;
public int y;
public Point(int startX, int startY) {
x = startX; // 明明這裡可以直接存取到x ?
y = startY; // 明明這裡可以直接存取到y ?
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(100, 200);
}
}
```
有了this, 你可以這樣寫:
```java=
class Point {
public int x;
public int y;
public Point(int x, int y) {
/*
this就是指現在這個物件參考
也就是 剛剛new出來的物件參考
*/
this.x = x;
this.y = y;
}
public void print() {
System.out.println(this.x + " " + this.y);
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(100, 200);
p.print();
}
}
```
因為上述寫法中, 建構子中的參數x, y把field x, y隱藏住了,
如果在建構子中寫x, 指的是參數x, 而不是field x,
所以要以this.x 表明是field的x.
## 在Constructor使用this
你可以在呼叫建構子時, 呼叫另一個建構子。
這叫做"explicit constructor invocation"
```java
class Point {
public int x;
public int y;
public Point() {
/*
this.x = -1;
this.y = -1;
*/
this(-1, -1);
}
public Point(int x, int x) {
this.x = x;
this.y = y;
}
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point();
System.out.println(p1.x + " " + p1.y); // -1 -1
Point p2 = new Point(100, 200);
System.out.println(p2.x + " " + p2.y); // 100 200
}
}
```
## getter, setter
```java
class Point {
private int x;
public int y;
public Point() {
this(-1, -1);
}
public Point(int x, int x) {
this.x = x;
this.y = y;
}
public void getX() {
return this.x;
}
public int setX(int x) {
this.x = x;
}
public void getY() {
return this.x;
}
public void setY(int y) {
this.y = y;
}
}
```