#440 - A Class Can Implement More than One Interface

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.

 1 public class Cow: IMoo, IMakeMilk

 2 {

 3     public void Moo()

 4     {

 5         // do mooing here

 6     }

 7 

 8     public double Milk()

 9     {

10         // do milking here

11     }

12 }     

You can now use an instance of the Cow class to access members of either interface.

1 Cow bossie = new Cow("Bossie", 12);

2 

3 // Call both IMoo and IMakeMilk methods

4 bossie.Moo();                        // IMoo.Moo

5 double numGallons = bossie.Milk();   // IMakeMilk.Milk

We can also set interface variables of either interface type to an instance of a Cow.

1 IMoo mooStuff = bossie;

2 IMakeMilk milkStuff = bossie;

3 

4 mooStuff.Moo();

5 numGallons = milkStuff.Milk();

原文地址:#440 - A Class Can Implement More than One Interface

你可能感兴趣的:(interface)