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