2

What access modifier should I use for my constructors in an abstract class, given that the class cannot be instantiated? It seems like the access modifier is superfluous and should be implicitly protected since it can only be used from within a derived class' constructor via base().

1

As you mentioned, your options are protected and private.

protected seems like a good default, but don't forget about the case where you don't want your sub classes to invoke a specific constructor. For example:

public abstract class AbstractBase
{
    private AbstractBase(int foo, double bar)
    {
        this.CalculatedProperty = someComplexCalculation(foor, bar);
    }

    protected AbstractBase(string XXX, string YYY, int foo, double bar)
        : this(foo, bar)
    {
        this.XXX = XXX;
        this.YYY = YYY;
    }

    protected AbstractBase(string XXX, int foo, double bar)
        : this(XXX, "There is no YYY.  There is only XXX.", foo, bar)
    {
    }

// *snip*

}

In this (overly simplified) example, we guarantee that the values for foo, bar, and XXX are always specified and that CalculatedProperty and XXX are always set.

The private constructor allows us to have shared construction logic without code duplication. And, because it's private, sub-classes can't accidentally partially construct themselves.

  • So what is the purpose of having a public constructor, which is not disallowed? – rory.ap Jun 19 '15 at 14:02
  • It's not disallowed, it's simply functionally equivalent to a protected constructor. With that said, I would still avoid using the public modifier here simply because if you modify your class in the future and make it concrete then your constructor is suddenly more accessible than intended. – MetaFight Jun 19 '15 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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