我理解如果一个类实现了包含相同名称的默认方法的多个接口,那么我们需要在子类中重写该方法,以便明确定义我的方法将执行的操作.问题是,请参阅下面的代码:
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的打印方法,我不明白为什么!
If a method declaration
d1
with return typeR1
overrides or hides the declaration of another methodd2
with return typeR2
,thend1
must be return-type-substitutable ford2
,or a compile-time error occurs.
A method declaration
d1
with return typeR1
is return-type-substitutable for another methodd2
with return typeR2
iff any of the following is true:
If
R1
isvoid
thenR2
isvoid
.If
R1
is a primitive type thenR2
is identical toR1
.If
R1
is a reference type then one of the following is true:
R1
,adapted to the type parameters ofd2
,is a subtype ofR2
.
R1
can be converted to a subtype ofR2
by unchecked conversion.
d1
does not have the same signature asd2
,andR1 = |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; }
}