I read this Oracle's article about Interfaces in Java. I think, that the provided example is bad. They use the following example:
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;
}
}
Is it acceptable to cast Relatable other
to RectanglePlus
? I think, not. In my understanding, such implementation will fails in case if this class will be used via interface reference, and someone will try to compare it with another implementation of Relatable
, that isnt' actually an instance of RectanglePlus
. And I think, that such usage of interfaces is valid, while the problem is in the implementation.
What do you think? May be I don't understand something?