Object Oriented Programming/Interfaces

= Interfaces =

An Interface allows a class to expose a different set of properties and methods depending on context. For example, say that you were writing a Visual Basic 2005 application that manages clients. A client could be an individual person, or an organization. Part of the program generates address labels for clients.

You might define a person like this:

You might also define an Organization like this:

As you can see, the main differences between a Person and an Organization are:
 * a Person has both a first name and a last name, while an organization has only a single name
 * an Organization has a separate mailing address, while a Person only has one address

So that you can have the one routine to print address labels, you create an interface called "IAddressLabel" (by convention, the name of an interfaces should start with a capital I).

You now change the Person class to implement this interface. The main thing to notice is that the Person's first and last names are combined on the label.

You now change the Organization class to implement the IAddressLabel interface. Notice that the address for the label is the mailing address, not the building address.

Now you can group the disparate objects together as a collection of address labels!

Interfaces vs. Inheritance
Interfaces and Inheritance can both be used to solve the problem of treating dissimilar objects collectively. For example, if you have a Cat class and a Dog class, but have some routine that needs to process them together, you could either:
 * Create an Animal base class, which contains procedures common to both Cats and Dogs, and have Cat and Dog inherit from Animal, or
 * Create an IAnimal interface, and have both Cat and Dog implement the interface.

Which approach to use depends on several factors. In general:
 * If you are extending an existing class, then use inheritance. For example, if you already have an Animal class, and then discover a need to distinguish between Cats and Dogs
 * If you are simply wanting to treat different objects as the same, then use Interfaces. For example, you already have Cat and Dog classes, and then discover a need to manipulate them in a similar fashion