我阅读了 Oracle 的这篇关于 Java 接口的文章。我认为,提供的示例很糟糕。他们使用以下示例:
public interface Relatable {
public int isLargerThan(Relatable other);
}
public class RectanglePlus implements Relatable {
public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus) other;
if (this.getArea() < otherRect.getArea()) {
return -1;
}
else if (this.getArea() > otherRect.getArea()) {
return 1;
}
else {
return 0;
}
}
Relatable other
可以接受RectanglePlus
吗?我想不是。据我了解,如果此类将通过接口引用使用,则此类实现将失败,并且有人会尝试将其与 的另一个实现进行比较Relatable
,这实际上不是RectanglePlus
. 而且我认为,接口的这种用法是有效的,而问题在于实现。
你怎么看?可能是我不明白什么?