假设我有两个接口(interface):
public interface I1
{
default String getGreeting() {
return "Good Morning!";
}
}
public interface I2
{
default String getGreeting() {
return "Good Afternoon!";
}
}
如果我想同时实现它们,将使用什么实现?
public class C1 implements I1, I2
{
public static void main(String[] args)
{
System.out.println(new C1().getGreeting());
}
}
最佳答案
这是一个编译时错误。两个接口(interface)不能有两个实现。
但是,如果你在C1
中实现getGreeting
方法是正确的:
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 中是默认的,你也不能同时实现它们。所以这也是编译时错误:
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 - 在 Java 8 中实现两个具有相同签名的默认方法的两个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685930/