Abstract Base Classes

A situation may arise where you need to only inherit from a certain class, but need not instantiate objects of that class. In such a case the base class can be regarded as “incomplete”. Such classes are known as Abstract Base Classes. C# allows creation of Abstract Base Classes by an addition of the abstract modifier to the class definition. Instances of abstract base classes cannot be created.

These abstract base classes can only contain the method definitions, the actual implementation of the method is made only in the derived class. This means that the abstract base class holds only the function prototypes (the return type of the method, the name and the parameters it takes) but no code for the body (the implementation of the method, the code which defines what the method has to do). The body of the function is written in the derived class. The method with no implementation is known as an operation.

Consider the following example,

Example 5:

Abstract Base Classes Example 5

The output of Example 5 will be,

This is the AFunc() method!
This is the BFunc() method!

In Example 5 we have declared an abstract base class by the name ABC. Note that to declare a class as abstract we just need to add the abstract keyword to the regular class syntax.

  • An abstract base class can also contain methods with implementations, apart from containing abstract methods (operations).
  • The operations also need to be marked with an abstract keyword.
  • The operations definition always ends with a semi-colon.

Getting back to Example 5, we have created a new class named Derv, which derived from class ABC. Thus, the class Derv can override the abstract AFunc() method of its base class ABC.

To override the abstract method from the abstract base class the syntax is very similar to that of overriding a virtual function. All you have to do is,

Specify,

  • The keyword override.
  • Make sure that the method names are just the same, including the parameters.
  • Write the necessary code (implementation).

In Example 5, in the Main() method we have declared an object of type ABC (which is the Abstract Base Class). However, note here that we are just creating an object of type ABC, we are not instantiating an object of that type. If we try to instantiate the object, the C# compiler will generate an error as instances of ab abstract base class cannot be created.

When the AFunc() method of class ABC is called it automatically calls the overridden function of class Derv. Also note that we have created an object a of the type ABC (this Abstract Base class) and we have simply copied the object to another object (remember they belong to reference types so only the reference is copied). Now we can use object a just as object b. In the Main() function we have tried calling AFunc() and the BFunc() methods just as we do from object  b and, as you can see in the output, it works just the same.

Leave a comment