Requiring Inheritance


Certain classes are meant to be used as base classes. For example, in the case of a banking application, a developer may define a class called Account that has default implementations for methods like MakeDeposit and GetBalance . However, the intention of the class may be for other developers to build derived classes like Checking and Savings. You can require developers to derive from your class and prevent developers from creating instances of the class directly.

To require inheritance in your class:

  • Type abstract after the access modifier of the class and before the word class in the class declaration ( Figure 5.42 ).

    Figure 5.42 When you mark a class as abstract, you are telling the compiler not to allow a developer to create the class directly. It is only meant to be used as a template for other classes.
      abstract  class AbstractAccount {    // you can declare variables in    // abstract classes    protected decimal m_balance;    // default implementation of    // MakeDeposit    public virtual void MakeDeposit(                       decimal amount)    {      m_balance +=amount;    }    public decimal GetBalance()    {      return m_balance;    } } 

graphics/tick.gif Tip

  • Abstract classes can be used for declaring variables; you just can't create an instance of the abstract class ( Figure 5.43 ).

    Figure 5.43 It is illegal to create an instance of an abstract class. However, it is perfectly legal to use the abstract class as a data type and then assign it to an instance of a class that derives from the abstract class.
     abstract class AbstractAccount { } class Checking() : AbstractAccount { } class Bank() {    static void CreateAccount()    {      //you can declare a variable of      //type AbstractAccount  AbstractAccount acct =   new Checking();  //but you can't create an instance      //of the AbstractAccount directly      //this is illegal  AbstractAccount acct =   new AbstractAccount();  } } 



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