在 Java 8 中使用两个具有相同签名的默认方法实现两个接口 [英] Implementing two interfaces with two default methods of the same signature in Java 8
本文介绍了在 Java 8 中使用两个具有相同签名的默认方法实现两个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个接口:
public interface I1
{
default String getGreeting() {
return "Good Morning!";
}
}
public interface I2
{
default String getGreeting() {
return "Good Afternoon!";
}
}
如果我想同时实现它们,会使用什么实现?
If I want to implement both of them, what implementation will be used?
public class C1 implements I1, I2
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
}
推荐答案
这是一个编译时错误.两个接口不能有两个实现.
This is a compile-time error. You cannot have two implementation from two interfaces.
但是,如果你在C1
中实现了getGreeting
方法是正确的:
However, it is correct, if you implement the getGreeting
method in C1
:
public class C1 implements I1, I2 // this will compile, bacause we have overridden getGreeting()
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
@Override public String getGreeting()
{
return "Good Evening!";
}
}
我只想补充一点,即使I1中的方法是抽象的,而I2中的默认方法,您也不能同时实现它们.所以这也是一个编译时错误:
I just want to add that even if the method in I1 is abstract, and default in I2, you cannot implement both of them. So this is also a compile-time error:
public interface I1
{
String getGreeting();
}
public interface I2
{
default String getGreeting() {
return "Good afternoon!";
}
}
public class C1 implements I1, I2 // won't compile
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
}
这篇关于在 Java 8 中使用两个具有相同签名的默认方法实现两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文