Who is online? 112 guests and 0 members
Member login | Become a member
posted 7/9/2009 8:11:46 AM by vivek_iit
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.
vivek_iit (Member since: 11/27/2008 11:54:25 AM) I am one of the administrators at CodeAsp.Net and I love programming, architecting solutions, code reviews, teaching and writing about ASP.NET.
View vivek_iit 's profile
Leave a comment
It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.
enter your email address: