What are all the difference between an abstract class, and a class with only protected constructor(s)? They seem to be pretty similar to me, in that you can’t instantiate either one.
EDIT:
How would you create an instance in a derived class, with a base class with a protected constructor? For instance:
public class ProtectedConstructor
{
protected ProtectedConstructor()
{
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor(); // this is fine
}
}
public class DerivedClass : ProtectedConstructor
{
public void createInstance()
{
ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
}
public static ProtectedConstructor getInstance()
{
return new ProtectedConstructor(); // doesn't compile
}
}
You can instantiate a class with protected constructors from within the class itself – in a static constructor or static method. This can be used to implement a singleton, or a factory-type thing.
An abstract class cannot be instantiated at all – the intent is that one or more child classes will complete the implementation, and those classes will get instantiated
Edit:
if you call
ProtectedConstructor.GetInstance();instead ofnew ProtectedConstructor();, it works. Maybe protected constructors can’t be called this way? But protected methods certainly can.Here is an interesting article on the topic.