If we don't know about [the] implementation, just the requirement specification, then go for interface.
What that means is that you can sketch out an architecture by designing and writing the interfaces first, and defer writing the implementations that satisfy those interfaces to a later time.
Let's say you're one of the designers of the Java development environment. You want to provide a sort function for your collections. But you don't know how to sort custom types (i.e. user-defined classes) because you don't know how to determine whether one object of a given class is greater than another. You can't write an implementation for that comparison, because you don't know how to do that for any given class that someone may write.
So you provide an interface called Comparable
. It defines a method
int compare<T>(T other)
that takes as a parameter an "other" object of the specified type, and returns a number that tells Java whether the other object is equal, greater than or less than this
object. Now you can let people derive their class from your interface and write a Compare
method implementation. Your sort function now understands how to sort these objects because it understands Comparable
and can call their Compare
method to compare two instances of their objects.