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