Common Type System—Abstract Classes


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Common Type System

© 2006 Wiley Publishing Inc.

Abstract Classes

An abstract class is a class that cannot be instantiated. It represents a base class for other types to derive from. If a class isn’t abstract, it’s said to be concrete (although this is the default, so we ordinarily don’t mention the concreteness). Individual methods on an abstract class can also be marked as abstract, meaning that they don’t supply an implementation. Properties cannot be marked abstract. Abstract methods are what most C++ programmers know as pure virtual methods. An abstract class is not required to have abstract methods, but a type with abstract methods must be abstract.

For example, all four of these classes can be marked as abstract. Only examples 2 and 4 must be marked as abstract, because they contain abstract members:

// Abstract, no members
abstract class AbstractType1 {}
// Abstract, with only abstract members
abstract class AbstractType2
{
   public abstract void Foo();
   public abstract void Bar();
}
 
// Abstract, with only non-abstract members
abstract class AbstractType3
{
   public void Foo()
   {
      Console.WriteLine(“AbstractType3::Foo);
   }
 
   public void Bar()
   {
      Console.WriteLine(“AbstractType3::Bar);
   }
}
 
// Abstract, with a mix of abstract and 
// non-abstract members
abstract class AbstractType4
{
   public void Foo()
   {
      Console.WriteLine(“AbstractType4::Foo);
   }
 
   public abstract void Bar();
}

When a type subclasses an abstract class, it inherits all of the base type’s members, as is the case with ordinary classes. For methods that supply an implementation, that implementation is also inherited. But for methods that are marked abstract, the subclass must either provide an implementation for every single one or it may declare that it, too, is an abstract class.

For example, consider a class deriving from AbstractType4 from our example above:

class ConcreteType : AbstractType4
{
   public override void Bar()
   {
      // We must provide an implementation here, 
      // or else mark
      // ‘ConcreteType’ as abstract, too.
      Console.WriteLine("ConcreteType::Bar");
   }
}

Abstract types are marked with the abstract metadata token in the IL generated, and an abstract method is implicitly marked as both abstract and virtual. Thus, a derived class acts as though it were overriding any ordinary virtual method to supply an implementation. As with any other virtual method, an override cannot redefine a method’s visibility.


Previous_Page_.gif Next_Page_.gif


Personal tools