posted 7/9/2009 by Vivek Thakur
When should you use Abstract classes for implementing dynamic polymorphism? and when Interfaces are your best option?
Most beginners tend to get confused between Abstract classes and Interfaces, so here is a quick primer:
In Abstract classes you can use "abstract" keyword to mark methods which *must* to be implemented in derived classes, and use the "virtual" keyword to create some concrete methods which can be overridden in derived classes. So Abstract classes allow you to create method signatures as well as provide some functionality in terms of concrete overridable virtual methods.
Whereas in Interfaces, you can have only method (or property) signatures, and each implementation class has to implement *all* the methods/properties defined in the interface.
Interface Polymorphism
Implementing polymorphism via interfaces limits you because once your interface is defined, you cannot change it in future (else exisiting client implementations will break down). This means interfaces are immutable. So if you want to add new features you need to create a new interface. In .NET you can derive from multiple interfaces, but then with time you might have a lot of interfaces created just to accomodate the extra features you developed over time and this can cause maintenance as well as performance issues. Hence you need to spend good amount of time while re-factoring your exisitng code into interfaces to make sure you have captured each and every functionality possible in your interface.
Abstract Class Polymorphism
Abstract classes on the other hand are more flexible as they can accomodate extra features/changes without breaking exisiting clients. They are very useful when you want to "version" your software, like with newer upgrades and more features. I mostly tend to go with abstract class polymorphism because of the extra flexibility it provides.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18