0

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?

Victor Dombrovsky
  • 2,955
  • 3
  • 21
  • 33

1 Answers1

0

You're right. This code might throw a cast exception if isLargerThan is given a Relatable that isn't an instance of RectanglePlus (or any of its children)

They should have checked the Class of the object passed using instanceof.

Malt
  • 28,965
  • 9
  • 65
  • 105