CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Eric Wise

Business & .NET

Inheritance And Interfaces

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:

Public Class test
    Implements IComparable

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo

    End Function
End Class

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:

Public Class test
    Inherits Inheritable

    Sub New()
        Me.DoStuff()
    End Sub
End Class

Public Class Inheritable
    Public Function DoStuff() As Boolean
        'I'm doing stuff
        Return True
    End Function
End Class

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!



Comments

Raymond Lewallen said:

The simplest way to convey interface inheritance versus object inheritance is interface inheritance is a "has a" relationship. Your object that implements an interface "has" the properties and methods of the interface, nothing more. Object inheritance is a "is a" relationship. When class "Labrador" inherits from class "Dog", it "is" a dog. It has all the functionality and properties of a dog, plus some it adds on its own.

"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!"

Not necessarily true, although that can happen. The base class constructor can be doing particular things and make use of some private methods, instantiate other objects, etc that all setup the state for the derived object. This is common in data access layers where the base class creates the connection object and transaction object via its ctor and exposes these fields to the derived class, while everything thing else in the base class may be marked as MustOverride. An interface cannot do this.
# June 2, 2005 9:58 AM

Eric Wise said:

Ok, so the intent of that statement was "If you have a class with nothing but MustOverrides, then you have a interface". Putting code in the instantiation, etc violates what I was trying to say.
# June 2, 2005 10:18 AM

TomCat said:

rlewallen, type 'has' relationship is called composition like when a 'Dog' class has a 'Tail' class as one of it's properties.
# June 2, 2005 11:34 AM

Raymond Lewallen said:

TomCat, can see it both ways. Dog "has" a tail as a member as defined by the interface it implements.
# June 2, 2005 12:05 PM

Geoff Appleby said:

Now here's an interesting discussion opportunity.

In your test class, in the constructor, you put 'Me.DoStuff()'.

Now, what's the best thing to do here? There's Me.DoStuff, MyBase.DoStuff, MyClass.DoStuff

When you're not really considering future inheritance chains, what's the best to specify?

Me, unless I've specifically marked a method as Overridable, I like to specify MyBase instead of Me, because it makes it quite clear you've delegated the work down the inheritance chain, as opposed to having to search through a potentially long class looking for an override that may or may not exist.

Obviously MyClass has a very specific purpose - when you know a method could be overridden, but you really really want a non overridden version to be called, so it's not that often that it's used.

My feeling is that this is a mini-religious argument, just like VB vs C# and naming conventions...
# June 2, 2005 9:55 PM

Eric Wise said:

Personally, I always use "Me" unless of course I'm calling the base of an overridable member.

For some reason it just makes more sense to me. I think of it like, yes, the functionality is in the base class, but since I'm not overriding it for all practical purposes it is "Me/My" member now.
# June 3, 2005 6:39 AM

TomCat said:

rlewallen, I don't think 'has' make a lot of sense here because basically the class is implementing the interface which 'has' the properties.

Consider this:

IDog = new Dog(); // sorry shifting the post to C#

you can only do this because Dog 'is' an IDog and not 'has' IDog, right?
# June 3, 2005 10:03 PM

TomCat said:

gappleby, I would use this (Me) because if decide to overide the base method in the future and use it in my class, i don't have to go back and change my code to call it. And isn't that the purpose of inheretance?
# June 3, 2005 10:06 PM

Raymond Lewallen said:

TomCat, "is" implies you have an instance. Dog cannot be "is" an IDog because an IDog doesn't exist. You cannot have an instance of an interface, only an instance of that which implements the interface.
# June 6, 2005 6:33 AM

Barknee said:

Interface inheritance is an "implements" relationship and is in no way "has-a". Has-a relatinships are comprised of composition and aggregation concepts. In the dog example, if it is composition then the dog always has that tail and when the dog dies so does the tail. Aggregation passes the tail on to someone else for use on some other dog, or worse yet some other animal completely. Has-a is therefore some sort of containment(agg or comp) and not interface inheritance.
# June 9, 2005 8:02 AM

Barknee said:

This is what is wrong with properties in interfaces. Properties tend to take away from "implement"ing and interface. I tend to stay away from Properties in interfaces because of this. One thing to look at and go back to OO 101 is, well, would you ever have the need to have an IDog interface? It's a noun, therefore a class. Now, speak is a different idea altogther. Interfaces represent verbs. Properties tend to cause this type of thinking when you think of interfaces. Now if you look at it in terms of a composite relationship, IE GOF Composite, Speak would be the abstract or interface method called speak and your dog can now speak: woof. Your cat can meow. :-0
# June 9, 2005 8:59 AM

J Donnici said:

The trackback doesn't seem to be getting picked up, but here are two more cents on the subject:

http://jeff.donnici.com/archive/2005/06/11/247.aspx
# June 11, 2005 10:08 AM

Barknee said:

J,

I agree with you on most, but respectfully disagree on a few others. Has-a doesn't "imply" composition. In fact I would venture a guess that with the "properties" craze in .NET not many developers could tell you the difference between read-only or composition or aggregation. So, what I am saying is, aggregation is usually the default, right or wrong.

I would say that inheritance is often underused especially on larger projects but that also depends on where in the system we are talking about. Domain models require inheritance and advanced OO concepts, however in a messaging subsystem it may not be as important. Using composition/aggregation can sometimes solve a problem but it can create to many interdependencies throughout a system. Large systems that rely on a composition/aggregation design paradigm often get in trouble when changes are made to the system. This is a nightmare in very large systems. Now, I am not saying that one or the other is better. As with all things, figure out which fits in the situation you are in.

When I start designing something, I will always model classes that could be interfaces as abstract classes(interface yes) and then if in time they must become pure interfaces they are changed. I then like to look at "realization" vs "generalization" for interfaces. How are objects realized vs how are the generalized by their clients.
# June 13, 2005 5:04 AM

Ravi Varma said:

I agree what u said as interface "has a" relationship since it has only the properties but in inheritance "is a" means it is a part of the base class.
# June 16, 2006 5:49 AM

Sreejith said:

If I override all the methods of a class.Does that mean that class is an Interface

# September 24, 2006 10:27 AM

Lea Go said:

Greetings,

As what i read on this posted article, i found out the informativeness of this

kind of topic. For that reason i opened up an idea and some knowledge in this

field. well, you made just did a great job..more power!

sincerely,

Lea Go

<a href="http://www.dogcontainmentsystems-4less.com">Dog Containment Systems</a>

# April 11, 2007 2:01 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!

Our Sponsors

Free Tech Publications