Abstract class and constructor

2019-07-02 14:52发布

问题:

As an abstract class cannot be instantiated, why is a constructor still allowed inside the abstract class?

public abstract class SomeClass 
 {  
     private string _label;

     public SomeClass(string label)  
     {  
         _label=label;
     }  
}

回答1:

Constructors of any derived class still have to call a constructor in the abstract class. If you don't specify any constructors at all, all derived classes will just have to use the default parameterless one supplied by the compiler.

It absolutely makes sense to have a constructor - but "public" is really equivalent to "protected" in this case.



回答2:

Because you can still do the following:

public class SomeChildClass : SomeClass
{
    public SomeChildClass(string label) : base(label){ }

    public string GetLabel() { return _label; }
}

As you can see, the child class can call the base contructor (on the abstract class) to create an instance of itself.

Like Jon said though, public really isn't necessary. It's effectively the same as protected.