Explain C# Abstract class constructor with Real Time Example

(Last Updated On: February 11, 2018)

Answer includes C# abstract class constructor with real time example program. An interviewer can also ask it as, can abstract class have constructor in C# program ? If yes, why do we use constructor in abstract class? etc.

Answer: Yes, an abstract class can have a constructor, even though abstract class cannot be instantiated. An abstract class constructor c# code example will be explained. But, next question can also be arises, as if we cannot instantiate (construct object using new) an abstract class, then what for an constructor is in an abstract class or why should we use a constructor in abstract class?

Before abstract class constructor uses discussion, note that when we create an object of a derived class then constructor of abstract base class is implicitly called, even though we cannot instantiate an abstract class. For example in program, if we create object of derived class then abstract base class constructor will also be called.

Output:
Abstract class constructor
Derived class constructor

 

As per C# abstract constructor uses point of view, it is possible that we may want to initialize some libraries before constructing the derived classes object in the software projects.

For example in below program example given, before object construction of derived classes i.e. “Music” and “Video” class, we may want to initialize some music/video database libraries in their base abstract class (Features in below example) itself. So, we need a constructor in abstract class to initialize database libraries.

Secondly, an abstract class can have implementation of methods and some of the fields, it is using might need to be initialized to default.

C# Abstract class constructor example :

In below program, “Features” class is an abstract base class and “Music” and “Video” classes are the derived classes form abstract class.In Features abstract class constructor, we have initialized music, video database libraries. Also, we have initialized username and password fields to default.

On construction of derived Music class object, database library will be initialized by base class itself. Abstract class function “login()” implementation will be using default field username and password.

 

Output:

Abstract class constructor
Initializing Music/Video database library
Music Constructor
Music downloading…

Abstract class constructor
Initializing Music/Video database library
Video Constructor
Video downloading…