版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82902027
接口中的默认方法和抽象方法像示例方法一样可以被继承,当类的超类或者接口提供多个相同签名的默认方式时,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());
}
}
接口的静态方法不会被继承