-1

Everywhere I see, there are blogs, content, notes that say Abstract classes cannot be instantiated.

Now in c# I created a sample code, something like this:

public abstract class Fundamental
{
    public Fundamental()
    {
        Console.WriteLine("This is an abstract constructor");
    }
}

Now why does the comipler suggest that the constructor must be protected. Why does it even allow a constructor.

I know what we can do a class instantiation like this,

Fundamental instance = new LessFundamental();

where less fundamental is this:

public class LessFundamental : Fundamental { }

But why the constructor. Also I can use internal, protected, public on this abstract class constructor. At some places it is mentioned that

You can still extend the abstract class and call the abstracts class' constructor in your derived class

But when would one need it?

Which design scenario does it cater to

4
  • An abstract class with a public constructor is perfectly legal, but the fact that the class is abstract means that the constructor can only be called from it's derived classes, and therefor it's safe to make it protected. It's not obligatory, but recommended since the constructors of an abstract class are effectively protected, even when they are declared as public. Jan 14, 2019 at 10:59
  • 1
    @ZoharPeled: the question remains why it's "perfectly legal" if you can't call it from everywhere Jan 14, 2019 at 11:00
  • That's a good question that I haven't found a good answer to, yet. It has been asked before but none of the answers seems to give a good reason why the compiler allows a public constructor on an abstract class. My guess is that it just never was a high priority for the compiler team to forbid it. Jan 14, 2019 at 11:13
  • Another good read while we're on the subject of abstract classes and constructors is this. Jan 14, 2019 at 11:14

1 Answer 1

3

It cannot be instantiated directly. But it can from a subclass that inherits from that abstract class. Therefore, if it can only be instantiated from a subclass, then the constructor should be protected rather than public.

Not the answer you're looking for? Browse other questions tagged or ask your own question.