When to create an abstract class?

Ricky White
Ricky White used Ask the Experts™
Abstract class is often defined as a class that cannot be instantiated.

I am not clear what is the use of such a class. Why would I want to create a class like that?

Can somebody give a few example situations when somebody should create an abstract class?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
If you want to ensure that a class implements certain methods, then you can create an interface.  But an interface cannot have any implementation, all implementation must be provided by the user of the interface.  

An abstract class,  on the other hand, can ensure that the class implements certain methods, but it can also provide a default implementation.
AndyAinscowFreelance programmer / Consultant
An example.
You could for instance have an abstract class - Animal.  This has certain properties/functions such as number of legs...
You could then have a further abstract class - Reptile - that is based on Animal.  Another abstract class could be Mammal, also based on Animal.
Now you could have 'real' classes such as Cat (based on Mammal), Crocodile (based on Reptile) and so on.

That way you just have one location for all the common code (number of legs....)
For example, in a current project I have a "xyzCollectionBase" that is abstract.  I don't want to ever instantiate this class so it is abstract. This class only contains one method but I do have a bunch of subclasses and this saves me from having to define the same method in each one.
Of course, the "xyz" in my previous comment is not the real name of the class.   Another example from a current project is an "xyzDataItem" class.  In this one, I have several abstract methods to ensure that the subclasses implement the methods.  And it also contains several implemented methods so that the subclasses don't have to.
You can have abstract properties too:  public abstract TypeEnum EntryType { get; }
nice answer AndyAinscow
AndyAinscowFreelance programmer / Consultant



So an abstract class always has to be a base class right? It should not be a child class?

Thanks all!
Subclasses can be abstract too.
AndyAinscowFreelance programmer / Consultant

>>So an abstract class always has to be a base class right? It should not be a child class?

In my example you saw an abstract class was a child of another abstract class.  What you can NOT do is create an instance of an abstract class.
In my example the following does not work.
Reptile r = new Reptile();

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial