重載和重寫的區別

重載和重寫的區別

重載(Overload)

重載:在同一個類中,多個方法具有相同的方法名,但是方法的參數列表不同(參數類型、參數個數或順序不同)。
重載是一個類中多態性的表現,調用相同方法名方法時,根據傳遞的參數來決定使用哪個方法,在編譯時已經對方法進行綁定(編譯時的多態性)

public class FunOverload {

    public static void main(String[] args) {

        FunOverload test = new FunOverload();
        int num1 = 1;
        int num2 = 2;
        long num3 = 3L;
        System.out.println(test.add(num1, num2));   //輸出結果:3
        System.out.println(test.add(num1, num2, num2)); //輸入結果:5
        System.out.println(test.add(num1, num3));   // 輸入結果:4

    }

    public int add(int num1, int num2) {
        return num1 + num2;
    }

    public int add(int num1, long num2) {
        return num1 + num2;
    }

    public int add(int num1, int num2, int num3) {
        return num1 + num2 + num3;
    }

}

重寫(Override)

重寫:在子類繼承父類時,子類定義的方法和父類中的方法具有相同的方法名,相同的參數列表和兼容的返回類型,又稱爲方法覆蓋。
重寫在子類與父類間呈現出多態性,當父類引用變量賦值爲子類對象,並調用子類中的重寫方法,此時在程序運行時會調用子類中經過重寫的方法(方法的動態綁定),而不是父類中定義的方法,在調用時纔對方法進行綁定(運行時的多態性)
注:子類中不能重寫父類中的final方法;
子類中必須重寫父類中的abstract方法;

public class Father {

    public static void main(String[] args) {

        Father children = new Children();
        Father father = new Father();
        children.sayHello();    //輸出:Class Children say: Hello
        children.saySon();      //輸出:Class Father say: Come on, baby
        father.sayHello();      //輸出:Class Father say: Hello
        father.saySon();        //輸出:Class Father say: Come on, baby

    }

    public void sayHello() {
        System.out.println("Class Father say: Hello");
    }

    public void saySon() {
        System.out.printlin("Class Father say: Come on, baby");
    }

}

public class Children extends Father {

    public void sayHello() {
        System.out.println("Class Children say: Hello");
    }

}

重載和重寫的區別

方法的重載和重寫都是多態性的實現,區別在於前者實現的是編譯時的多態性,而後者實現的是運行時的多態性。
重載發生在一個類中,同名的方法如果有不同的參數列表(參數類型不同、參數個數不同或者二者都不同)則視爲重載。重載對返回類型沒有特殊的要求,不能根據返回類型進行區分;
重寫發生在子類與父類之間,子類重寫父類方法時需要有相同的參數列表,有兼容的返回類型,比父類方法更好訪問,不能比父類方法聲明更多的異常(里氏代換原則)。

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