Benefits of using an abstract classes vs. regular class

ryanzec picture ryanzec · Jul 6, 2010 · Viewed 43.3k times · Source

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?

Answer

AlvinfromDiaspar picture AlvinfromDiaspar · Jul 6, 2010

Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...

Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.

Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).