Java複習筆記(十)super關鍵字

super關鍵字

super關鍵字代表了父類空間的引用。

一、super關鍵字的作用:

1.子父類存在着同名的成員時,在子類中默認是訪問子類的成員,可以通過super關鍵字指定訪問父類的成員。

注意:這裏是訪問父類的成員,包括成員變量和成員函數

class Fu{
    int x = 10;
    public void out(){
        System.out.println("x = "+x);
    }
}

class Zi extends Fu{
    int x = 20;
    public void out(){
        System.out.println("x = "+x);
    }
    public void outFu(){
        System.out.println("x = "+super.x);
    }
    public void Fuout(){
        super.out();
    }
}

public class Mian {
    public static void main(String[] args)
    {
        Zi z = new Zi();
        z.out();
        z.outFu();
        z.Fuout();
    }
}
//運行結果
x = 20
x = 10
x = 10

2.創建子類對象時,默認會先調用父類無參的構造方法,可以通過super關鍵字指定調用父類的對應傳參構造方法。

class Fu{
    String name;
    public Fu(){
        System.out.println("Fu類無參的構造方法..");
    }
    public Fu(String name){
        this.name = name;
        System.out.println("Fu類帶參的構造方法..");
    }
}


class Zi extends Fu{
    int num;
    public Zi(String name,int num){
        super(name); //指定調用了父類帶參的 構造方法...
        //this(); // 調用本類無參構造方法..
        //super(); //指定調用了父類無參構造方法。。。
        System.out.println("Zi類帶參的構造方法..");
    }
    public Zi(){
        System.out.println("Zi類無參的構造方法..");
    }
}

public class Mian {
    public static void main(String[] args)
    {
        Zi z = new Zi("chenjipayen",38);
    }
}

二、super關鍵字要注意的事項:

1.如果在子類的構造函數中沒有指定調用具體父類構造函數,那麼java編譯器會在子類的構造函數上添加super()語句。

2.super關鍵字調用構造函數時必須出現構造函數中第一個語句。
3.this與super調用構造函數的時候不能同時出現在一個構造函數中,因爲都需要是第一個語句。

class Zi extends Fu{
    int num;
    public Zi(String name,int num){
        super(); //指定調用了父類無參構造方法..
        this(); // 調用本類無參構造方法..
        System.out.println("Zi類帶參的構造方法..");
    }
    public Zi(){
        System.out.println("Zi類無參的構造方法..");
    }
}
//Call to 'this()' must be first statement in constructor body

三、super關鍵字與this關鍵字的區別:

1.代表的事物不一致。
  super關鍵字代表的是父類空間的引用。
  this關鍵字代表的是所屬函數的調用者對象。
2.使用前提不一致。
  super關鍵字必須要有繼承關係才能使用。
  this關鍵字不需要存在繼承關係也可使用。
3.調用構造函數的區別:
  super關鍵字是調用父類的構造函數。
  this關鍵字是調用本類的構造函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章