0

我阅读了 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. 而且我认为,接口的这种用法是有效的,而问题在于实现。

你怎么看?可能是我不明白什么?

4

1 回答 1

0

你是对的。isLargerThan如果给定的Relatable不是RectanglePlus(或其任何子)的实例,则此代码可能会引发强制转换异常

他们应该检查使用传递的对象的类instanceof

于 2016-06-22T16:34:07.367 回答