Hi Serge.
I usually view Interfaces as a way to provide "abilities" to certain
objects.
for example, if I want an object to be able to look like an Animal, I would
create an interface that would describe an animal, and name it
appropriately. for example - "IAnimal".
the "I" in the beginning denotes that this is an Interface.
Let's say to an animal, in my case would be able to eat and drink.
So in the interface I would create two methods name "Eat()" and "Drink()".
Now, every object that would like to be able to become an animal(or
represent itself as an animal) must implement this interface, meaning it
must implement "Drink()" and "Eat()" and should be marked as implementing
IAnimal .
in C# you would write:
public Interface IAnimal
{
void Eat()
{//no code here}
void Drink()
{//no code here}
}
public class MyObject : IAnimal
{
void Eat()
{
//do some eating code here
}
void Drink()
{
//do some drinking code here
}
}
now. because this is an interface and each class can implement it
differently, we only write the code of the methods of the interface inside
the classes that implement that interface.
So for example, I could have a "Dog" class and a "Cat" class and they would
both implement IAnimal.
Each one can implement the eat and drink methods differently, but because
they both implement the IAnimal interface, I can write generic code like
this to handle both types of classes with very simple code:
//notice that I receive the Interface, not an actual class
void MakeAnimalDrinkAndEat(IAnimal animal)
{
//I call the actual class that implements the interface here
animal.Drink()
animal.Eat()
}
void main()
{
Dog MyDog = new Dog();
Cat MyCat = new Cat();
//notice that I don't care what kind of class I send to that
//method as long as that class implements the IAnimal interface
MakeAnimalDrinkAndEat(MyDog)
MakeAnimalDrinkAndEat(MyCat)
}
The behavior shown here is called "Polymorphism" - the ability of an object
to appear in different shapes. Implementing interfaces allows this.
In this case the "MyDog" class instance was able to show itself both as a
"Dog" class, and both as an "IAnimal".
Now, see how powerful this is: If I now create a new object, let's say
"Elephant", and I want it to be able to eat and drink and being treated like
an Animal - I make it implement IAnimal, and I can send that object to the
"MakeAnimalDrinkAndEat" method. I *gave* it the ability to be an animal.
This is it on a very quick discussion.
For more about interfaces see this:
http://www.superdotnet.com/show_article.aspx?pkID=136
--
Regards,
Roy Osherove
http://www.iserializable.com
---------------------------------------------