Amutha
Amutha

Reputation: 35

Abstract class and constructor

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;
     }  
}

Upvotes: 3

Views: 472

Answers (2)

Justin Niessner
Justin Niessner

Reputation: 245389

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499740

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.

Upvotes: 11

Related Questions