在Java 8中使用两个具有相同签名的默认方法实现两个接口 [英] Implementing two interfaces with two default methods of the same signature in Java 8

查看:92
本文介绍了在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.

但是,如果你实现 getGreeting 方法,这是正确的。 C1

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆