Jon Jagger
jon@jaggersoft.com
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 8 Language Overviewprevious at this levelnext at this level 8.7 Classesprevious at this levelnext at this level 8.7.11 InheritanceClasses support single inheritance, and the type object is the ultimate base class for all classes. The classes shown in earlier examples all implicitly derive from object. The example
using System;  
class A  
{  
   public void F() { Console.WriteLine("A.F"); }  
}  
shows a class A that implicitly derives from object. The example
class B: A  
{  
   public void G() { Console.WriteLine("B.G"); }  
}  
class Test  
{  
   static void Main() {  
      B b = new B();  
      b.F();    // Inherited from A  
      b.G();      // Introduced in B  
      
      A a = b;     // Treat a B as an A  
      a.F();  
   }  
}  
shows a class B that derives from A. The class B inherits A's F method, and introduces a G method of its own.
Methods, properties, and indexers can be virtual, which means that their implementation can be overridden in derived classes. The example
using System;  
class A  
{  
   public virtual void F() { Console.WriteLine("A.F"); }  
}  
class B: A  
{  
   public override void F() {   
      base.F();  
      Console.WriteLine("B.F");   
   }  
}  
class Test  
{  
   static void Main() {  
      B b = new B();  
      b.F();  
      A a = b;   
      a.F();  
   }  
}   
shows a class A with a virtual method F, and a class B that overrides F. The overriding method in B contains a call, base.F(), which calls the overridden method in A.
A class can indicate that it is incomplete, and is intended only as a base class for other classes, by including the modifier abstract. Such a class is called an abstract class. An abstract class can specify abstract members-members that a non-abstract derived class must implement. The example
using System;  
abstract class A  
{  
   public abstract void F();  
}  
class B: A  
{  
   public override void F() { Console.WriteLine("B.F"); }  
}  
class Test  
{  
   static void Main() {  
      B b = new B();  
      b.F();  
      A a = b;  
      a.F();  
   }  
}  
introduces an abstract method F in the abstract class A. The non-abstract class B provides an implementation for this method.
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS