I also agree with adamalex's response that interfaces should be shared by classes that should respond to certain methods.
If classes have similar functionality, yet are not directly related to each other in an ancestral relationship, then an interface would be a good way to add that function to the classes without duplicating functionality between the two. (Or have multiple implementations with only subtle differences.)
While we're using a car analogy, a concrete example. Let's say we have the following classes:
Car -> Ford -> Escape -> EscapeHybrid
Car -> Toyota -> Corolla -> CorollaHybrid
Cars have wheels
and can Drive()
and Steer()
. So those methods should exist in the Car
class. (Probably the Car
class will be an abstract class.)
Going down the line, we get the distinction between Ford
and Toyota
(probably implemented as difference in the type of emblem on the car, again probably an abstract class.)
Then, finally we have a Escape
and Corolla
class which are classes that are completely implemented as a car.
Now, how could we make a Hybrid vehicle?
We could have a subclass of Escape
that is EscapeHybrid
which adds a FordsHybridDrive()
method, and a subclass of Corolla
that is CorollaHybrid
with ToyotasHybridDrive()
method. The methods are basically doing the same thing, but yet we have different methods. Yuck. Seems like we can do better than that.
Let's say that a hybrid has a HybridDrive()
method. Since we don't want to end up having two different types of hybrids (in a perfect world), so we can make an IHybrid
interface which has a HybridDrive()
method.
So, if we want to make an EscapeHybrid
or CorollaHybrid
class, all we have to do is to implement the IHybrid
interface.
For a real world example, let's take a look at Java. A class which can do a comparison of an object with another object implements the Comparable
interface. As the name implies, the interface should be for a class that is comparable, hence the name "Comparable".
Just as a matter of interest, a car example is used in the Interfaces lesson of the Java Tutorial.