Sitemap

Introduction to Object Oriented Interfaces

2 min readApr 13, 2018

--

Hello there reader! Today I’m going to explain interfaces that are so common to object oriented styles of programming.

Lets imagine a world where all animals either have thorns or do not. Now lets say all animals with thorns can poke other animals.

For example, (new Hedgehog("Sonic")).Poke(new Dog("Benny")); is how we would have a hedgehog poke a dog.

For example, say we have an army of thorny animals. We could include both hedgehogs and thorny dragons. Even though they are very distantly related with one being a mammal and the other being a reptile.

Using inheritance alone the only way to get these animals into one type would be to allow our army to include any animals. Not good, this is an army made for poking and not all animal:

var army = new List<Animal>();
army.Add(new Hedgehog("Sonic"));
army.Add(new Dog("Benny"));
army.Add(new ThornyDragon("Pickles"));
army.ForEach(animal =>
{
// This won't work since not all animals know how to poke
animal.Poke(new Rabbit("Rabbit"));
}

The solution to this problem is interfaces!

Get Charles Bayley’s stories in your inbox

Join Medium for free to get updates from this writer.

Lets create an interface for all thorny animals called IThorny:

interface IThorny
{
void Poke(Animal toBePoked);
}

Unlike classes, interfaces are pretty useless on their own. To be useful we must implement the interface onto some classes:

class Animal
{
string Name { get; set; }
}
class Hedgehog : Animal, IThorny
{
void Poke(Animal toBePoked)
{
Console.WriteLine($"The hedgehog {this.Name} has poked {toBePoked.Name} with those tiny thorns hedgehogs have.");
}
}
class ThornyDragon : Animal, IThorny
{
void Poke(Animal toBePoked)
{
Console.WriteLine($"{this.Name} the thorny dragon slaps {toBePoked.Name} with a thorny tail.");
}
}

Now we can allow all thorny animals to implement our new IThorny interface. Then we can build our army of IThornies instead of animals:

var army = new List<IThorny>();
army.Add(new Hedgehog("Sonic"));
army.Add(new ThornyDragon("Pickles"));

var rabbit = new Rabbit("Rabbit"));
army[0].Poke(rabbit);
army[1].Poke(rabbit);

The above example would now work since we know everything that is an IThorny can poke animals.

To summarize, interfaces allow programmers to group abilities to preform actions within a type without specifying how that action is done. I hope you can see the value of being able to adding types to classes without specifying functionality.

Thanks for ready and I hope you enjoyed!

Working example below:

--

--