21

Why does an abstract class have constructor? What's the point? It's obvious that we cannot create an instance of an abstract class.

Adam Lear
  • 35,439
  • 12
  • 80
  • 98
Aslam Jiffry
  • 1,276
  • 5
  • 19
  • 49

2 Answers2

25

One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

   abstract class Animal
   {
       public string DefaultMessage { get; set; }

       public Animal()
       {
           Console.WriteLine("Animal constructor called");
           DefaultMessage = "Default Speak";
       }
       public virtual void Speak()
       {
           Console.WriteLine(DefaultMessage);
       }
   }

    class Dog : Animal
    {
        public Dog(): base()//base() redundant.  There's an implicit call to base here.
        {
            Console.WriteLine("Dog constructor called");
        }
        public override void Speak()
        {
            Console.WriteLine("Custom Speak");//append new behavior
            base.Speak();//Re-use base behavior too
        }
    }

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:
Animal constructor called
Dog constructor called
Custom Speak
Default Speak

Ehsan Sajjad
  • 59,154
  • 14
  • 90
  • 146
P.Brian.Mackey
  • 39,360
  • 59
  • 210
  • 327
7

You can still initialize any variables, dependencies and you can set up the signature of the constructors of the inherited classes.

You usually want abstract classes when you need to have different strategies for some particular cases, so it makes sense to be able to do everything else in the abstract class. And it's a good practice to make the constructor protected.

AD.Net
  • 13,062
  • 2
  • 26
  • 44