1. 程式人生 > >java遺珠之介面方法

java遺珠之介面方法

介面中的預設方法和抽象方法像示例方法一樣可以被繼承,當類的超類或者介面提供多個相同簽名的預設方式時,java編譯器就會用繼承規則來解決命名衝突,這些規則遵循兩個原則。

例項方法優先於介面預設方法

看下面的例子

class Horse {
    public String identifyMyself() {
        return "I am a horse.";
    }
}

interface Flyer {
    default public String identifyMyself() {
        return "I am able to fly.";
    }
} interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.
identifyMyself()); } }

最終會列印I am a horse.

如果超型別是同一個時,會選擇已經覆蓋了預設方法的那一個。

interface Animal {
    default public String identifyMyself() {
        return "I am an animal.";
    }
}

interface EggLayer extends Animal {
    default public String identifyMyself() {
        return "I am able to lay eggs."
; } } interface FireBreather extends Animal { } public class Dragon implements EggLayer, FireBreather { public static void main(String... args) { Dragon myApp = new Dragon(); System.out.println(myApp.identifyMyself()); } }

不僅僅是兩個接口才會如此哦,一個類一個介面也會如此,只要超型別相同,上面的程式碼改一下

interface Animal {
    default public String identifyMyself() {
        return "I am an animal.";
    }
}

interface EggLayer extends Animal {
    default public String identifyMyself() {
        return "I am able to lay eggs.";
    }
}

class FireBreather implements Animal {
}


public class Dragon extends FireBreather implements EggLayer {
    public static void main(String... args) {
        Dragon myApp = new Dragon();
        System.out.println(myApp.identifyMyself());
    }
}

結果也是一樣的,會選擇已經覆蓋了的那一個。

如果兩個或者多個獨立定義的預設方法衝突,或者是預設方法和抽象方法衝突,java編譯器就會產生錯誤,這時候你必須明確的去覆蓋這個方法。

程式碼如下:

interface OperateCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
        return 1;
    }
}

interface FlyCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
        return 2;
    }
}

public class FlyingCar implements OperateCar, FlyCar {
    // ...
    public int startEngine(EncryptedKey key) {
        return FlyCar.super.startEngine(key) + OperateCar.super.startEngine(key);
    }
}

你還可以用super去呼叫超型別的預設方法。

從超類繼承的例項方法還可以覆蓋抽象介面方法,看下面的例子。

interface Mammal {
    String identifyMyself();
}

class AHorse {
    public String identifyMyself() {
        return "I am a horse.";
    }
}

public class Mustang extends AHorse implements Mammal {
    public static void main(String... args) {
        Mustang myApp = new Mustang();
        System.out.println(myApp.identifyMyself());
    }
}

介面的靜態方法不會被繼承