Adding Functions that Must Be Overridden


A class may declare a method that doesn't have a default implementation, but which must be overridden. For example a class called Account may have a method called PrintInfo , and the method may use a property called AccountType . The AccountType property would have a different implementation in each class. Therefore the author of the Account class may define the AccountType function as a function that must be overridden.

To add a function that must be overridden:

  1. Type abstract in the function definition after the access modifier for the function and before the function's return type.

  2. Type a semicolon after the method declaration. Don't add curly brackets ( Figure 5.40 ).

    Figure 5.40 PrintInfo uses the GetAccountType function. However, GetAccountType is specific to each derived class. Therefore, we can mark GetAccountType as abstract which means that derived classes must override it. Virtual means that it is optional to override and that there is a default implementation; abstract means that it is required to override and there is no default implementation.
      abstract  class Account {    public void PrintInfo()    {      Response.Write("Account Type:" +  GetAccountType  );    }    // declared without curly braces or    // code    public  abstract  string  GetAccountType  (); } 
  3. Mark the class as a class that must be inherited. See the next section "Requiring Inheritance" for details.

graphics/tick.gif Tip

  • If you have too many functions that require overriding it is best to define interfaces for the set of overridable functions ( Figure 5.41 ).

    Figure 5.41 If you end up with too many abstract function and properties, it is better to declare an interface instead. Interfaces are discussed in Chapter 8.
      interface IAccount  {    void PrintInfo();    void LogInfo();    void CheckBalance();    void FileReport(); } 



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