Tổng quan
this và super là từ khóa đặc biệt: this tham chiếu instance hiện tại, super tham chiếu parent class instance.
Bảng so sánh
| Tiêu chí | this | super |
|---|---|---|
| Tham chiếu | Instance hiện tại của class | Instance của parent class |
| Gọi constructor | this() gọi constructor khác của cùng class |
super() gọi constructor của parent class |
| Truy cập method | Gọi method của class hiện tại | Gọi method của parent class (ghi đè) |
| Static context | Có thể dùng (vd: System.out.println(this.x) trong static method nếu x là static) |
Không thể dùng trong static context (compile error) |
Ví dụ minh họa
class A {
public int x, y;
public A(int x, int y) {
this.x = x;
this.y = y;
}
}
class B extends A {
public int x, y;
public B() {
this(0, 0); // gọi B(int, int)
}
public B(int x, int y) {
super(x + 1, y + 1); // gọi A(int, int)
this.x = x;
this.y = y;
}
public void print() {
System.out.println("Base class : {" + x + ", " + y + "}");
System.out.println("Super class : {" + super.x + ", " + super.y + "}");
}
}
public class Point {
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}
Kết quả
Base class : {0, 0}
Super class : {1, 1}
Base class : {1, 2}
Super class : {2, 3}
Giải thích
new B()→this(0,0)→super(1,1)→ A.x=1, A.y=1 → B.x=0, B.y=0new B(1,2)→super(2,3)→ A.x=2, A.y=3 → B.x=1, B.y=2super.xtruy cập field x của parent (A),this.xtruy cập của B.
Quy tắc quan trọng
this()hoặcsuper()phải là dòng đầu tiên trong constructor.- Không thể dùng cả hai trong cùng một constructor.
- Nếu không viết, Java tự chèn
super()(no-arg constructor của parent).