Oct 13, 2011

Interface for comparing objects

For example lets create an Interface Relatable that allows us to implement the isLargerThan() method to the class that implements this interface.

public interface Relatable {

// this (object calling isLargerThan) and
// other must be instances of the same class
// returns 1, 0, -1 if this is greater
// than, equal to, or less than other
public int isLargerThan(Relatable other);
}


If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable.

Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method.

If you know that a class implements Relatable, then you know that you can compare the size of the objects instantiated from that class.

MyRectangle Class implements Relatable interface. It must implement isLargerThan() method. Since MyRectangle class implements Relatable Interface, two objects of MyRectangle class can be compared.

// a method required to implement the Relatable interface
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;
}

Note:

The isLargerThan method, as defined in the Relatable interface, takes an object of type Relatable. The line of code, shown in bold in the previous example, casts other to a MyRectangle instance. Type casting tells the compiler what the object really is. Invoking getArea directly on the other instance (other.getArea()) would fail to compile because the compiler does not understand that other is actually an instance of MyRectangle.
Related reference that shows the similar Interface "Relatable"

When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.
Interface as type

Extending interface
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.

No comments:

Down with the Dictatorship!

    "Let them hate me, so that fear me" - Caligula 41AD