C# Abstract Class


This entry is part 7 of 10 in the series C# Inheritance

Abstract classes are designed to be inherited from. An abstract class can be used only as the base (parent) class of another class. You cannot create instances of an abstract class. An abstract class is declared using the abstract modifier. A sealed class is the opposite of an abstract class.

An abstract class can contain abstract members or regular, non-abstract members. The members of an abstract class can be any combination of abstract members and normal members with implementations. An abstract class can itself be derived from another abstract class.

Any class derived from an abstract class must implement all the abstract members of the class by using the override keyword, unless the derived class is itself abstract.

using System;
namespace AbstractIllustrated
{   // example from book Illustrated C# 7, 5th Edition  on page 207
    abstract class AbClass // Abstract class
    {
        public void IdentifyBase() // Normal method
        { Console.WriteLine("I am AbClass"); }

        abstract public void IdentifyDerived(); // Abstract method
    }
    class DerivedClass : AbClass // Derived class
    {
        override public void IdentifyDerived() // Implementation of
        { Console.WriteLine("I am DerivedClass"); } // abstract method
    }
    class Program
    {
        static void Main()
        {
            // AbClass a = new AbClass(); // Error. Cannot instantiate
            // a.IdentifyDerived(); // an abstract class.
            DerivedClass b = new DerivedClass(); // Instantiate the derived class.
            b.IdentifyBase(); // Call the inherited method.
            b.IdentifyDerived(); // Call the "abstract" method.
        }
    }
}
Series Navigation<< C# Boxing and UnboxingC# Masking Members of a Base Class >>