Wednesday, October 13, 2010

Difference between Abstract class and interface in layman's terms

A very good explanation of the difference between Abstract class and Interface that I found posted on MSDN Social Forum and a nice image explaining the same concept in different way.


A good way to distinguish between a case for the one or the other for me has always been the following:

1. Are there many classes that can be "grouped together" and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. (A key decider is that these classes share functionality, and you would never instantiate just an Animal... you would always instantiate a certain kind of Animal: an implementation of your Animal base class)
Example: Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (I might make this method virtual so that I can override it for certain animals, like Fish, which does not breath the same as most animals).

2. What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs.
Example: All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - I will not implement this on the base class, since this does not apply to Cat.

As said by someone else's reply: the main difference is where you want your implementation. By creating an interface, you can move your implementation to any class that implements your interface.
By creating an abstract class, you can share implementation for all derived classes in one central place, and avoid lots of bad things like code duplication.


Source:  

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/8ad621b8-a915-4d7e-89c3-5dbbc47202fd




Image source: http://www.codeproject.com/KB/architecture/Abstract_Interface/Logical1.jpg  

No comments:

Post a Comment