#440 – A Class Can Implement More than One Interface
October 25, 2011 Leave a comment
It’s possible for a class to implement more than one interface.
For example, a Cow class might implement both the IMoo and the IMakeMilk interfaces. Multiple interfaces are listed after the class declaration, separated by commas.
public class Cow : IMoo, IMakeMilk
{
public void Moo() { // do mooing here }
public double Milk() { // do milking here }
}
You can now use an instance of the Cow class to access members of either interface.
Cow bossie = new Cow("Bossie", 12);
// Call both IMoo and IMakeMilk methods
bossie.Moo(); // IMoo.Moo
double numGallons = bossie.Milk(); // IMakeMilk.Milk
We can also set interface variables of either interface type to refer to an instance of a Cow.
IMoo mooStuff = bossie;
IMakeMilk milkStuff = bossie;
mooStuff.Moo();
numGallons = milkStuff.Milk();