Using Interfaces for Polymorphism


Polymorphism is the idea that two related classes can have slightly different implementations for the same method. When using interfaces as types, a developer can define functions that accept any objects that implement the interface as parameters. Then, depending on what object you send to the function, the function will run slightly different code.

To use polymorphism:

  1. In any class define a function where one of the input parameters is a type of interface.

  2. Call methods of the interface.

  3. Pass any object to the function that supports the interface ( Figure 8.24 ).

    Figure 8.24 Notice that the type for the parameter in the Communicate function is type IHuman. You can pass any object to the function that implements the interface. All three classes implement the interface in different ways. The Communicate method will return a different string depending on what object you pass in.
     interface IHuman {    string Speak(); } class Baby : IHuman {    public string Speak()    {      return "Goo-goo gaa-gaa";    } } class Spouse : IHuman {    public string Speak()    {      return "Can I buy a new computer?";    } } class Friend : IHuman {    public string Speak()    {      return "Can I borrow some money?";    } } class Person {    string Communicate(  IHuman person  )    {      return person.Speak();    }    void DailyLiving()    {      string answer;      Spouse sp =  new Spouse()  ;      answer = Communicate(  sp  );      Friend fr =  new Friend()  ;      answer = Communicate(  fr  );      Baby ba =  new Baby()  ;      answer = Communicate(  ba  );    } } 

graphics/tick.gif Tip

  • Before passing an object to the function, make sure that the object in fact supports the interface (see "Interface Discovery" earlier in this chapter for details).




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