This post originated from an RSS feed registered with .NET Buzz
by Eric Wise.
Original Post: Inheritance And Interfaces
Feed Title: Eric Wise
Feed URL: /error.htm?aspxerrorpath=/blogs/eric.wise/rss.aspx
Feed Description: Business & .NET
A common question I get from developers new to OO programming and VB .NET is what the difference is between inheritance and interfaces, particularily when should you use one over the other.
At its most basic level, the difference between inheritance and interfaces is that inheritance is intended to allow you to share an implementation, while an interface specifies that you must implement something, but supply your own logic. Many people liken an interface to a "contract". To use an interface you must expose certain functionality, but the implementation of that functionality is up to you.
Make sense? No? Let's look at the IComparable interface in .NET:
When you implement IComparable, Visual Studio automatically puts the function signature CompareTo in for you. By implementing IComparable, you have to follow the contract that specifies that you must have a CompareTo function. To do otherwise would cause a compiler error.
Note that there is no code in this function. You've created a custom class test and you want to compare it to another object. The author of IComparable has no idea what criteria needs to be met for the objects to be considered equal, so they leave it to you to fill out.
In contrast, if you were to inherit a class, like in this example:
You'll notice that even though DoStuff() does not show up in the test class when inherited, it is still accessible by the test class. The code inside the parent class (inheritable) will execute the same for any class that inherits it.
So basically, if you created a class you intended other developers to inherit, but every single function/sub was marked as "MustOverride", then you've really created an interface!