Blocking Inheritance


Blocking inheritance is the opposite of requiring it. Certain classes block inheritance to prevent derived classes from overriding virtual methods that come from interfaces or from other base classes. For example the string class in .NET blocks inheritance. One reason may be that the string class overrides functions that determine things like equality. The class may make certain assumptions as to how these methods work. If the string class didn't block inheritance, any developer would be able to create a subclass and override how equality is determined and potentially invalidate some of the assumptions made in the original string class.

To block inheritance:

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

    Figure 5.44 There are at least three reasons why you may want to seal a class: 1) It doesn't make sense to inherit from the class; 2) All members are static (you should then also add a single private constructor to prevent creation); 3) You want to prevent overriding of all virtual methods.
      sealed  class Business : AbstractAccount {    public override void PrintInfo()    {      string s = "Savings - balance is: "             + this.m_balance.ToString();      System.Console.WriteLine(s);    } } 


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