Abstract class and constructor
As an abstract class cannot be instantiated, why is a constructor still allo开发者_StackOverflow社区wed inside the abstract class?
public abstract class SomeClass
{
private string _label;
public SomeClass(string label)
{
_label=label;
}
}
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.
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
.
精彩评论