Using Objects through Interfaces


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:

  1. Define a variable of the type of interface. Type ICar var , for example.

  2. 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;    } } 

graphics/tick.gif 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.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net