views:

73

answers:

3

I usually make a base class abstract to give the signal this is a base class - you cannot instantiate me! even if there are no abstract methods in it.

Furthermore, I always make the base class constructor protected, although there's no real functional need to do that - I just want to make another point that this is a base class - you cannot instantiate me!

Am I jumping through hoops in doing that? What do you do?

+8  A: 

It seems a reasonable thing to do, yes. There'll be no functional difference between the constructor being public or being protected, but making it protected gives a clearer indication of the intended use.

Jon Skeet
@Jon: Also, if another dev down the road accidentally removes `abstract` from the class or `protected` from the ctor without thinking about the consequences, the added safety belt in having both of them there will remind him if the original contract is ever broken.
Johann Gerell
+2  A: 

I'm not sure that you should set the class as abstract if there are no abstract methods. If it has a full implementation of the functionality that is expected of the classes derived from it, why not let it be instantiated and used as is? If this is just a way to share functionality across a range of classes then a composition based design may be more appropriate ie. have each 'derived' class reference this class rather than derive from it.

Is there a particular scenario you have in mind where this is could be an appropriate design?

Edit
The only scenario I have found where an abstract class with no abstract methods makes sense is when the abstract class is partially implementing and interface. The derived classes are required to complete the implementation. Link to example

Dave Turvey
I think it's ok to have an abstract class without abstract methods in some cases. Fruit can be an abstract concept, and Orange and Apple the concrete ones, and it makes no sense to instantiate a Fruit.
bloparod
If your concrete classes (Orange and Apple) only exist to differentiate between types of fruit you are adding complexity to your design for little benefit. The same effect could be achieved by adding a Name property to the Fruit class. Also, all concepts are abstract to some extent. Apple is an abstract concept that encapsulates all the variety of apples eg Golden Delicious or Granny Smith.
Dave Turvey
+1  A: 

In an abstract class, there's no difference between a public or protected constructor. As a matter of fact, I believe the compiler should give a warning or error when defining the constructor of an abstract class as public. Too bad it doesn't.

SiN