Say you have a class called circle and a class called rectangle.
They are completely different, one has corners, the other is smooth, and
so on.
Yet, you have a method that takes either a circle or an rectangle and uses
their Volume or Surface property.
If you make an IGeometricObject interface (always use I to indicate
interface) you can pass any class "subscribing" to IGeometricObject and
not worry about wether the object is rectangle or circle.
interface IGeometricObject
{
public float GetVolume(); // a method all subscribers will have to
implement
public float GetSurface(); // anther such method
}
class Rectangle : IGeometricObject
{
public float GetVolume()
{
// TODO: Add Rectangle.GetVolume implementation
return 0;
}
public float GetSurface()
{
// TODO: Add Rectangle.GetSurface implementation
return 0;
}
}
class Circle : IGeometricObject
{
public float GetVolume()
{
// TODO: Add Circle.GetVolume implementation
return 0;
}
public float GetSurface()
{
// TODO: Add Circle.GetSurface implementation
return 0;
}
}
class SomeClass
{
public SomeClass()
{
Circle aCircle = new Circle();
Rectangle aRectangel = new Rectangle();
float number = calculateStuff(aCircle) + calculateStuff(aRectangle);
}
private float calculateStuff(IGeometricObject geo)
{
return geo.GetVolume() * geo.GetSurface();
}
}
So, if you have two different classes, but they both share some common
stuff, or you want them to share something (like being sortable in an
ArrayList, just "subscribe" to IComparer and/or IComparable) you use
interfaces.
You may look upon interfaces as building blocks for your class.
You have your basic class, maybe inherited from another class, and then
you add several interfaces to make it even more useful.
Visual Studio .Net will even fill in the required methods by pressing the
tab key when you add an interface.