什麼是this
代表指向當前類的一個引用,比如當前類是A,那麼this就指代指向類A的引用。
什麼是super
是一個關鍵字,可以指導編譯器調用父類的相關的可訪問資源(非private).。
特別注意!!
super並不指向父類的引用,他只是一個關鍵字,讓你操控父類的相關資源而已,而this則指我這個類實實在在的引用,我們可以從java核心技術第一卷中的chapter5看到這句話
Some people think of super as being analogous to the this reference.
However, that analogy is not quite accurate: super is not a reference to an
object. For example, you cannot assign the value super to another object
variable. Instead, super is a special keyword that directs the compiler to
invoke the superclass method.
大概意思就是說,super不是一個對象的引用,你不能把他賦值給另一個對象變量,這是和this不一樣的,我們可以寫代碼看看:
public class F extends SimpleDateFormat {
public void m1(){
F f = this; // 這麼做是允許的
F g = super; // 這是不允許的,編譯器會報錯
}
public static void main(String[] args) throws IOException {
}
}
關於用法
用法的話相信大家都很清楚的,
- 用於調用構造方法
class P{
public P(){
System.out.println("P constructor invoke");
}
}
class C extends P{
public C(){
// 無參調用有參
// this("test");
// 調用父類構造
super();// 這句其實也是隱式存在的,即便你不寫。
System.out.println("C constuctor invoke");
}
public C(String s){
System.out.println("C parameter constructor invoke");
}
}
- 用於調用成員方法
class P{
public void m1(){
System.out.println("p m1");
}
}
class C extends P{
public void m1(){
// 這是調用的父類的m1方法
super.m1();
}
}
- 用於調用成員變量(比如局部變量和成員變量名稱衝突的時候)
class P{
String v1;
public void setV1(String v1) {
this.v1 = v1;
}
public P(){
System.out.println("P constructor invoke");
}
}
class C extends P{
String v1;
public void setV1(String v1) {
// 此處是局部變量v1賦值給此類中的v1
this.v1 = v1;
// 下面是父類中的v1賦值給此類中的v1
this.v1 = super.v1;
}
public C(){
// 無參調用有參
this("test");
System.out.println("C constuctor invoke");
}
public C(String s){
System.out.println("C parameter constructor invoke");
}
}