Once a developer defines an interface and implements the interface in a concrete class, a developer using the class can use the class through the interface.
To use a class through an interface:
Define a variable of the type of interface. Type ICar var , for example.
Set the interface variable equal to an instance of a class that implements the interface. Type = new Escort(); for example ( Figure 8.21 ).
Figure 8.21 Although the variable's type is ICar you can't say new ICar. You have to create an instance of a class that implements the interface. Interfaces are not creatable types.
interface ICar { string Run(); string Stop(); string PlayMusic(); } class Escort : ICar { public string Run() { return "I'm running as fast as I can!"; } public string Stop() { return "Oh good, I finally get to stop"; } public string PlayMusic() { return "We are the pirates who don't do anything..."; } } class Driver { public string GoToWork() { ICar car = new Escort(); string msg = ""; msg+= car.Run(); msg+= car.PlayMusic(); msg+= car.Stop(); return msg; } }
Tip
You can't create instances of an interface. An interface is an abstract type, which means that it is not a creatable class. Instead you create instances of a class that implements the interface.