Re-Implementing Interfaces in a Derived Class


Re-Implementing Interfaces in a Derived Class

If you read the topic of Refactoring earlier in this chapter, you know that it's possible to create a base class that supports an interface, and then write derived classes from that base class. The derived classes will also support the interface. However, sometimes it makes sense to override one or more of the implementation methods in the derived classes. For that purpose you could re-implement the interface in the derived class.

To re-implement the interface in a derived class:

  1. After the name of the derived class type a colon followed by the name of the interface you wish to re-implement.

  2. Add an implementation for only the methods you wish to do differently from the base class ( Figure 8.29 ).

    Figure 8.29 The Dog class implements the IAnimal interface. GreatDane derives from Dog so it picks up the implementation of IAnimal. But what if GreatDane wants to implement the Speak method in IAnimal differently from Dog's implementation and keep the implementation of Eat? Then you can re-implement IAnimal in GreatDane and re-implement the methods you want to change.
     interface IAnimal {    string Speak();    string Eat(); } class Dog : IAnimal {    string IAnimal.Speak()    {      return "woof! woof!";    }    string IAnimal.Eat()    {      return "Yum!";    } } class GreatDane : Dog ,  IAnimal  {  string IAnimal.Speak()  {      return "Big woof! Big woof!";    } } 

graphics/tick.gif Tip

  • Another way of re-implementing the interface method is to mark the original implementation method as a virtual method and then override it in the subclass ( Figure 8.30 ).

    Figure 8.30 This method requires the author of the base class to mark the method virtual, which isn't always possible.
     interface IAnimal {    string Speak();    string Eat(); } class Dog : IAnimal {    public  virtual  string Speak()    {      return "woof! woof!";    }    public string Eat()    {      return "Yum!";    } } class GreatDane : Dog {    public  override  string Speak()    {      return "WOOF! WOOF!";    } } 



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