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
    }
}
@H_502_7@

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

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

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

最佳答案
这是不可能的.

8.4.8.3

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

8.4.5

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

  • If R1@H_502_7@ is void@H_502_7@ then R2@H_502_7@ is void@H_502_7@.

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

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

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

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

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

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

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

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

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...