Java 8 – 两个接口包含具有相同方法签名但返回类型不同的默认方法,如何覆盖?

我理解如果一个类实现了包含相同名称方法的多个接口,那么我们需要在子类中重写该方法,以便明确定义我的方法将执行的操作.问题是,请参阅下面的代码

interface A {
    default void print() {
        System.out.println(" In interface A ");
    }
}

interface B {
    default String print() {
        return "In interface B";
    }
}

public class C implements A,B {

    @Override
    public String print() {
        return "In class C";
    }

    public static void main(String arg[]) {
        // Other funny things
    }
}

现在,接口A和B都有一个名为’print’的方法,但我想覆盖接口B的print方法 – 返回字符串并按原样保留A的打印方式.但是这段代码不能编译给出:

Overrides A.print
The return type is incompatible with A.print()

很明显,编译器试图覆盖A的打印方法,我不明白为什么!

最佳答案
这是不可能的.

8.4.8.3

If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2,then d1 must be return-type-substitutable for d2,or a compile-time error occurs.

8.4.5

A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2 iff any of the following is true:

  • If R1 is void then R2 is void.

  • If R1 is a primitive type then R2 is identical to R1.

  • If R1 is a reference type then one of the following is true:

    • R1,adapted to the type parameters of d2,is a subtype of R2.

    • R1 can be converted to a subtype of R2 by unchecked conversion.

    • d1 does not have the same signature as d2,and R1 = |R2|.

换句话说,void,primitive和reference-returns方法可能只会被相同的相应类别的方法覆盖和覆盖. void方法可能只覆盖另一个void方法,引用返回方法可能只覆盖另一个引用返回方法,依此类推.

您遇到的问题的一种可能解决方案可能是使用组合而不是继承:

class C {
    private A a = ...;
    private B b = ...;
    public A getA() { return a; }
    public B getB() { return b; }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


应用场景 C端用户提交工单、工单创建完成之后、会发布一条工单创建完成的消息事件(异步消息)、MQ消费者收到消息之后、会通知各处理器处理该消息、各处理器处理完后都会发布一条将该工单写入搜索引擎的消息、最终该工单出现在搜索引擎、被工单处理人检索和处理。 事故异常体现 1、异常体现 从工单的流转记录发现、
线程类,设置有一个公共资源 package cn.org.chris.concurrent; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @Descrip
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量
Java 9中JShell中的不同启动脚本是什么?
使用Java的位填充错误检测技术
java中string是什么
如何使用Java中的JSON-lib API将Map转换为JSON对象?
Java菜单驱动程序以检查数字类型
使用Junit的Maven项目 - 检查银行账号
JAVA编程基础
在Java中使用throw、catch和instanceof来处理异常
在Java中,将数组分割为基于给定查询的子数组后,找到子数组的最大子数组和
如何在Java中从给定的字符串中删除HTML标签?
在PHP中,IntlChar getBlockCode()函数的翻译如下:
如何在Android中实现按下返回键再次退出的功能?
如何使用Java中的流式API解析JSON字符串?
Java中的模式类