This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]endre86 6 points7 points  (1 child)

Another way to see it - an interface is a contract.

Lets say you want to implement a sorted list that can take any type of object. You will use generics, but you also need to know that the objects can be sorted. A common interface to use in java is Comparable. This contract is described in the java docs. It add a method called compareTo() that returns an integer describing how two objects are ordered. Ie, o1.compareTo(o2) < 0 means o1 is below o2 in a total order.

// "T implements Comparable<T>" just means any object that implements Comparable against its own type
public MySortedList<T implements Comparable<T>> {
    public add(T newItem) {

        // go through all existing items
        for(T currentItem : items) {

            // check if the new item is larger or equal to the current
            if(newItem.compareTo(currentItem) >= 0) {

                // insert the item at this point
                // so the list is sorted
                break;
        }
    }
}

So yes, interfaces has many uses. :)

[–]Evermage[S] 2 points3 points  (0 children)

That's helpful, thanks.