#820 – A Protected Constructor Allows a Subclass to Create Instances
April 11, 2013 Leave a comment
You can declare a constructor as private to prevent client code from directly instantiating an object. But then you can no longer subclass the class, because the derived class won’t have access to the constructor.
If you want private constructor semantics, but still be able to create a subclass, you can make a constructor protected. Other code won’t be able to construct instances of the base class, but your subclass will be able to call the constructor.
public class Dog { public string Name { get; set; } public int Age { get; set; } protected Dog() { Console.WriteLine("Constructing Dog"); } }
public class Terrier : Dog { public double FeistyFactor { get; set; } // Implicitly invokes default constructor in base class public Terrier(string name, int age, double feistyFactor) { Console.WriteLine("Constructing Terrier"); Name = name; Age = age; FeistyFactor = feistyFactor; } }