Mulder
Mulder

Reputation: 2927

Constructor of an abstract class in C#

Why is it possible to write constructor for an abstract class in C#?
As far as I know we can't instantiate an abstract class.. so what is it for?
You can't instantiate the class, right?

Upvotes: 273

Views: 276145

Answers (15)

Jeetasha Jeetasha
Jeetasha Jeetasha

Reputation: 11

Using abstract classes is a way of standardizing your code. It can also be considered as a way of preparing a template or blueprint for other classes. Think about different types of cars that are available now days :- SUV, Sedan, Coupe, Hatchback etc. All have the same basic blueprint, for instance they all have steering, brake, clutch etc. But still there are many features and functionalities that are different in all the cars. So we can think of it as that an abstract class of car has been declared that includes the standardized methods/features that need to be implemented by all the cars but additionally the different types of cars can add their own features/functionalities as well. Now coming to your question and relating it to the example given above. See if we have to make a car obviously it would be one of a kind mentioned above (SUV,Sedan.....) i.e. for creating an instance of abstract class we need to inherit it. That is why it is termed as "must inherit class". If the constructor is also being included in the abstract class then it means that all the derived classes would also need to use a constructor as well. And if we are running a code of this kind :-

public abstract class AbstractClass
{
    public AbstractClass()
    {
        Console.WriteLine("Abstract class constructor");
    }
}
public class derived : AbstractClass 
{ 
    public derived()
    {
        Console.WriteLine("Derived class constructor");
    }
}
class Program
{
    public static void Main(string[] args)
    {
        derived d= new derived();
        Console.ReadLine();
    }
}

Then the output would be :-

    Abstract class constructor
    Derived class constructor

which clearly shows that constructor can also be used in abstract classes.

Upvotes: 1

akhil
akhil

Reputation: 1883

Adding to the above answers and examples.

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

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

This is also one of the example

Examples

abstract class A
{
    protected A() {Console.WriteLine("Abstract class constructor"); }
}
//Derived class
class B : A
{
   public B() {Console.WriteLine("Derived class constructor"); }
}

class Program
{
    static void Main(string[] args)
    {
        B obj = new B();
    }
}

Output will be

Abstract class constructor
Derived class constructor

Upvotes: 8

Sakib
Sakib

Reputation: 181

Key Points About Abstract Class

  1. An abstract class cannot be instantiated.
  2. An abstract class can have constructor and destructor.
  3. An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited.
  4. An abstract class contains abstract as well as non-abstract members.
  5. An abstract class members can be private, protected and internal.
  6. Abstract members cannot have a private access modifier.
  7. Abstract members are implicitly virtual and must be implemented by a non-abstract derived class.

Upvotes: 6

Rohan Rao
Rohan Rao

Reputation: 2603

You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.

Upvotes: 2

Ahmad
Ahmad

Reputation: 1524

From https://msdn.microsoft.com/en-us/library/ms182126.aspx

Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

Since only derived classes can use an abstract class constructor then an abstract class constructor, if needed, must be declared as protected.

However, that said VS compiler will not complain (with default rules) when declaring public constructors in abstract classes however it will not allow creating a new instance.

Upvotes: 0

pawan
pawan

Reputation: 1

There are two following important features that prevent to inherit Abstract class

  1. Abstract class must have an abstract method otherwise it is not a abstract class

  2. Abstract class must be inherited by derived class,So if a class inherited by other class than what is use of to create object of that class

Upvotes: -2

waqar ahmed
waqar ahmed

Reputation: 335

an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.

Upvotes: 0

supercat
supercat

Reputation: 81115

Defining a constructor with public or internal storage class in an inheritable concrete class Thing effectively defines two methods:

  • A method (which I'll call InitializeThing) which acts upon this, has no return value, and can only be called from Thing's CreateThing and InitializeThing methods, and subclasses' InitializeXXX methods.

  • A method (which I'll call CreateThing) which returns an object of the constructor's designated type, and essentially behaves as:

    Thing CreateThing(int whatever)
    {
        Thing result = AllocateObject<Thing>();
        Thing.initializeThing(whatever);
    }
    

Abstract classes effectively create methods of only the first form. Conceptually, there's no reason why the two "methods" described above should need to have the same access specifiers; in practice, however, there's no way to specify their accessibility differently. Note that in terms of actual implementation, at least in .NET, CreateThing isn't really implemented as a callable method, but instead represents a code sequence which gets inserted at a newThing = new Thing(23); statement.

Upvotes: 0

zafar
zafar

Reputation: 2064

Normally constructors involve initializing the members of an object being created. In concept of inheritance, typically each class constructor in the inheritance hierarchy, is responsible for instantiating its own member variables. This makes sense because instantiation has to be done where the variables are defined.

Since an abstract class is not completely abstract (unlike interfaces), it is mix of both abstract and concrete members, and the members which are not abstract are needed to be initialized, which is done in abstract class's constructors, it is necessary to have constructors in the abstract class. Off course the abstract class's constructors can only be called from the constructors of derived class.

Upvotes: 1

Craig Suchanec
Craig Suchanec

Reputation: 10804

Because there might be a standard way you want to instantiate data in the abstract class. That way you can have classes that inherit from that class call the base constructor.

public abstract class A{

    private string data;

    protected A(string myString){
      data = myString;
    }

}

public class B : A {

     B(string myString) : base(myString){}

}

Upvotes: 362

Sumit Kapadia
Sumit Kapadia

Reputation: 385

I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents

abstract classes are normal classes with A few exceptions

  1. You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
  2. It may has abstract function.

Upvotes: 0

duedl0r
duedl0r

Reputation: 9424

You can instantiate it after you implemented all the methods. Then the constructor will be called.

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 659956

Far as I know we can't instantiate an abstract class

There's your error right there. Of course you can instantiate an abstract class.

abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();

There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.

Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.

Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.

Upvotes: 282

Rodrick Chapman
Rodrick Chapman

Reputation: 5543

It's a way to enforce a set of invariants of the abstract class. That is, no matter what the subclass does, you want to make sure some things are always true of the base class... example:

abstract class Foo
{
    public DateTime TimeCreated {get; private set;}

    protected Foo()
    {
         this.TimeCreated = DateTime.Now;
    }
}

abstract class Bar : Foo
{
    public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
    { }
}

Don't think of a constructor as the dual of the new operator. The constructor's only purpose is to ensure that you have an object in a valid state before you start using it. It just happens to be that we usually call it through a new operator.

Upvotes: 27

Ross Anderson
Ross Anderson

Reputation: 136

It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).

Any class which inherits from your abstract base class will be obliged to call the base constructor.

Upvotes: 5

Related Questions