开发者

Abstract class and constructor

开发者 https://www.devze.com 2022-12-27 02:55 出处:网络
As an abstract class cannot be instantiated, why is a constructor still allo开发者_StackOverflow社区wed inside the abstract class?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消