Abstract Class

.Abstract Class


Abstract Class Program Output

.Abstract Class

"A C# program to illustrate abstract classes. Two classes are derived from the abstract class. The derived classes have different implementations of the abstract method."

The program defines a base class containing two integer values and an abstract method. Two derived class create different implementations of the abstract method. The following C# features are used in the sample code:

  1. Abstract Modifier - Indicates missing or incomplete implementation
  2. Abstract Classes - Can leave the implementation of methods until a specific implementation of that class is needed.
  3. Abstract Methods - Introduces a new virtual method but does not provide an implementation.
  4. Inheritance - Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

    Abstract Class

    namespace abstractClass
    {
        abstract class CalcClass // Abstract Class (for Base Class)
        {
            protected int x = 13;
            protected int y = 6;
            public abstract int DoOperation(); // Abstract Method
        }

        class Adder : CalcClass // Derived Addition Class
        {
            public override int DoOperation()
            {
                return x + y;
            }
        }

        class Subtractor : CalcClass // Derived Subtraction Class
        {
            public override int DoOperation()
            {
                return x - y;
            }
        }

        class Program
        {
            static void Header()
            {
                System.Console.WriteLine("*******************************************");
                System.Console.WriteLine("*** Abstract Class with Abstract Method ***");
                System.Console.WriteLine("*******************************************\n");
                System.Console.WriteLine("Classes derived from an abstract class with different method implementations.");
                System.Console.WriteLine("Operands: (13,6).\n");
            }

            static void Main()
            {
                Program.Header();

                // Prints: Adder result is: 19
                System.Console.WriteLine("\n------- DoOperation Method from Adder Derived Class -------");
                Adder myAdder = new Adder();
                System.Console.WriteLine("Adder.DoOperation() result is: {0}", myAdder.DoOperation());

                // Prints: Subtractor result is: 7
                System.Console.WriteLine("\n------- DoOperation Method from Subtractor Derived Class -------");
                Subtractor mySubtractor = new Subtractor();
                System.Console.WriteLine("Subtractor.DoOperation() result is: {0}\n", mySubtractor.DoOperation());
            }
        }
    }