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.

1using System;
2namespace AbstractIllustrated
3{   // example from book Illustrated C# 7, 5th Edition  on page 207
4    abstract class AbClass // Abstract class
5    {
6        public void IdentifyBase() // Normal method
7        { Console.WriteLine("I am AbClass"); }
8 
9        abstract public void IdentifyDerived(); // Abstract method
10    }
11    class DerivedClass : AbClass // Derived class
12    {
13        override public void IdentifyDerived() // Implementation of
14        { Console.WriteLine("I am DerivedClass"); } // abstract method
15    }
16    class Program
17    {
18        static void Main()
19        {
20            // AbClass a = new AbClass(); // Error. Cannot instantiate
21            // a.IdentifyDerived(); // an abstract class.
22            DerivedClass b = new DerivedClass(); // Instantiate the derived class.
23            b.IdentifyBase(); // Call the inherited method.
24            b.IdentifyDerived(); // Call the "abstract" method.
25        }
26    }
27}
Series Navigation<< C# Boxing and UnboxingC# Masking Members of a Base Class >>