1. 程式人生 > >super()調用父類構造方法

super()調用父類構造方法

構造方法 void main 實例 調用父類 方法 The public 如果

super()表示調用父類中的構造方法

1、子類繼承父類,子類的構造方法的第一行,系統會默認編寫super(),在調用子類的構造方法時,先調用父類的無參數構造方法

2、如果父類中只有有參數構造方法,那麽子類繼承父類時會報錯,因為子類的構造方法在默認調用父類無參數構造方法super()不存在。

3.如果子類的第一行編寫了this()、this(實參),因為this()也會占用第一行,所以此時就會將super()擠掉,就不會調用父類構造方法。

實例1.子類的構造方法會默認在第一行先調用父類無參數構造方法super()

//父類
public class Father
{

    
int id; public Father() { System.out.println("調用父類中的構造方法"); } } //子類 public class Son extends Father { public Son() { System.out.println("調用子類構造方法"); } } //測試類 public class Test { public static void main(String[] args) { Son s
= new Son(); } }

//結果是:先調用父類無參數構造方法,在調用子類構造方法
技術分享圖片

 

實例2:父類中沒有參數構造方法

//父類中編寫有參數構造方法,覆蓋無參數構造方法
public class Father
{

    int id;
    //定義有參數構造方法
    public Father(int id)
    {
        System.out.println("調用父類中的構造方法");
    }
}

//子類繼承父類
//因為父類中沒有無參數構造方法,所以會子類繼承父類時會報錯
技術分享圖片

 

我們可以通過在子類中調用父類有參數構造方法來避免這種錯誤,

//定義父類,並且編寫有參數構造方法覆蓋無參數構造方法
public class Father
{

    int id;
    
    //編寫有參數構造方法覆蓋無參數構造方法
    public Father(int id)
    {
        System.out.println("調用父類中的構造方法");
    }
}


//定義子類
public class Son extends Father
{
    public Son()
    {

               //在構造方法中調用父類有參數構造方法
        super(10);
        System.out.println("調用子類構造方法");
    }

}

//編寫test類

public class Test
{
    public static void main(String[] args)
    {
        Son s = new Son();
    }

}

測試結果:
技術分享圖片

 

也可以在構造方法中調用本類中其他構造方法,來擠掉super()調用父類中無參數構造方法

//父類
public class Father
{

    int id;
    
    //
    public Father(int id)
    {
        System.out.println("調用父類中的構造方法");
    }
}

//子類
public class Son extends Father
{
    //無參數構造方法
    public Son()
    {
        //手動編寫調用父類有參數構造方法
        super(10);
        System.out.println("調用子類構造方法");
    }
    
    //有參數構造方法
    public Son(int i)
    {
        //調用本類其他構造方法,擠掉super()
        this();
        System.out.println();
    }

}

super()調用父類構造方法