super()調用父類構造方法


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();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM