DevCity.NET - http://devcity.net
OOP Basics - Introduction to Inheritance
http://devcity.net/Articles/396/1/article.aspx
Ged Mead

Ged Mead (XTab) is a Microsoft Visual Basic MVP who has been working on computer software and design for more than 25 years. His journey has taken him through many different facets of IT. These include training as a Systems Analyst, working in a mainframe software development environment, creating financial management systems and a short time spent on military laptop systems in the days when it took two strong men to carry a 'mobile' system.

Based in an idyllic lochside location in the West of Scotland, he is currently involved in an ever-widening range of VB.NET, WPF and Silverlight development projects. Now working in a consultancy environment, his passion however still remains helping students and professional developers to take advantage of the ever increasing range of sophisticated tools available to them.

Ged is a regular contributor to forums on vbCity and authors articles for DevCity. He is a moderator on VBCity and the MSDN Tech Forums and spends a lot of time answering technical questions there and in several other VB forum sites. Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, and DevCity.NET Newsletter Editor. He has written and continues to tutor a number of free online courses for VB.NET developers.

 
by Ged Mead
Published on 5/15/2010
 
This article is the next in the series on the subject of OOP Basics.  It takes a first look at the important topic of Inheritance.

Introduction

While you are creating any new class you will continually be assessing what properties and methods should be included and, just as importantly, which should be left out.   

The decision will always depend on the particular class you are creating, what its purpose is, where it fits into the order of things.   If you find yourself in doubt as to whether a class should include a particular member, a good rule of thumb is to leave it out.    If it will cause more confusion than clarity, leave it out.   If it will be of no use in a majority of scenarios, leave it out.   The danger is that if you include too much specialised functionality in a general base class, you restrict its usefulness.

To take the Chess Club scenario that I’ve been using in this series of articles, for example, it makes perfect sense to have the Forename, Surname, Date  of Birth and Gender properties in a class named “Person”.    A value can be assigned to all person instances for each of those four items of information.

But what if we wanted to create a property that stored the Date that a Person instance joined the Chess Club?   All Chess Club members are persons, but all persons are not Chess Club members.   It wouldn’t make sense to have such a property in the very generalised Person class.     What would make far more sense and would give the greatest flexibility would be to have a Person class that contains those four core properties and have a separate class that contains those four properties, plus the “Date Joined Chess Club” one.

   And there lies the solution.  Inherited classes.  Create a brand new class that  inherits all the previously created members (Properties, Fields, Methods, Events) from the Person class and add any further functionality that your more specialised class needs.    We briefly saw this happening in an earlier section when we learned that our Person class inherits the functionality of the System.Object class.

   You may remember that I described this as a Parent-Child relationship. Let's have a look at how this works and create a child class of our own for the Chess Club project.

Creating Derived Classes

   As I explained earlier in the series, in order to show inheritance in action, our overall Chess Club structure includes several classes:  a ClubMember class, a Sponsor class and a ClubOfficial class.   The hierarchy of these classes is shown below.

 

     As you can see, ClubMember and Sponsor both have Person as a parent class.   In real world terms, this makes perfect sense as all instances of ClubMembers and Sponsors will be Persons, with names, dates of birth and gender.  

     In our Chess Club situation, ClubOfficials must be members of the club.   Therefore it is logical that they inherit all the functionality of the ClubMember class, which in turn, as we have just seen, will inherit from the Person class.

     Let’s begin by creating the ClubMember class.

 

The ClubMember Class

If you've been following along with this series of articles and building up the Chess Club project, open up your Class Basics project.   Add a new class to the project and name this class ClubMember. 

In the code window for this class add the line “Inherits Person”.

        Public Class ClubMember
       Inherits Person

 

   Even if you didn’t add a single jot of code to this class, you already have a bunch of functionality.      We could create a new ClubMember instance and it will have available all the inherited members (those properties and methods we created earlier) of the parent or base class, Person.   

 

    Want to see a demonstration of this?   In the Form_Load event of the Windows form in the Class Basics  project, type in the following code :

 

     Dim cm As New ClubMember

   cm.

 

As soon as you enter the period after “cm”, Intellisense will provide you with a list of the available properties and methods, as you can see in the screenshot below:     

 

You'll probably recognise that list as being the same one that would be displayed if you were creating a new Person instance. Clearly then, the new ClubMember instance – cm - inherits all the Public properties and methods of its parent class, Person. You didn’t have to write any additional code to achieve this, except for the keyword “Inherits”.

So far, so good, but the purpose of creating the derived class, ClubMember, is to enable us to extend the facilities of the base class, Person. So let’s go ahead and do that, by creating a Public property for the ClubMember class.

The DateJoined Property

One property that might be really useful in the Chess Club scenario is one that allows client code to get or set a value for the date that a club member joined the Chess Club.     I'll call this property DateJoined.
For the reasons I outlined at the start of this set of articles, I'll use a Private field to store the values that are passed in via the property (and to pass values out from it also).    This field will be named m_datejoined.

If you've been following along the steps in the series, you should be completely confident of creating the field and the property yourself at this stage, so go ahead and add them to the ClubMember Class code file.   Once you've done this, you can check your version with the sample shown below.

 

You may have used a different default value for the m_datejoined field, but if the rest of your snippet is the same, then you're on track.

By the way, if your code looks like this:

 

 

Then give yourself a big pat on the back for paying attention in the earlier articles!    It isn’t strictly necessary to include the validation, but it seems to make sense in this situation. 

Next, we will take a look at constructors for the derived class.

 

ClubMember Class Constructors

Right back in the first article, when I created the Person class, I recommended that you include a default constructor with no parameters.  That is:

 

The same applies to your inherited classes too.  I advise you to include a parameterless constructor in the new derived ClubMember class.    In fact, if you haven’t taken the advice and neither the Person class nor  the Club Member class have parameterless constructors, then you will get a compile error as soon as you try to run the project using the derived class.

MyBase, as you will recall, refers to the Base class that the current class is derived from.   So, in the case of the Person class, MyBase refers back to System.Object.     In the case of the ClubMember class, MyBase refers back to the Person class.

What Happened to the Inherited Constructor?

Here’s a strange thing, you may think.    We understood that the child class inherits the Public members of the parent class.    Constructors are often included in a list of members of a class and they are Public by default.   So you would expect that constructors are also inherited.     But, actually they’re not.    It’s enough to make you want to give up this OOP business and go back to your old procedural code, isn’t it?  

Anyway, don’t give up just yet!  First, try entering the following code in the project’s form:

 

As you can see from the screenshot above, the wavy blue line is the code editor’s way of telling you that there's something wrong and it isn’t happy.

If you hover the cursor over the parameters (“Jenny”, “Wren”), you will see the problem:

 

This error message confirms that the ClubMember class doesn't (yet) have a constructor that will accept those two strings as parameters.

So, is it time to sigh and start writing out clones of the base class constructors by hand in the derived class?    Happily not.   We don’t inherit base class constructors automatically but you can certainly still get to use them.
 
Here’s how:    Add this constructor code to the ClubMember class:-

 

 

Now, if you retry the "Jenny Wren" code shown above, that failed previously, you'll find that it works just fine.

In case you're thinking that this hasn’t saved an awful lot of writing, then in this particular case I’d have to agree.  But if the base class constructor had been long, complex and included several pieces of validation code, then the time and effort saved would certainly have been worthwhile.  

So how does this actually work?  Well, what happens here is that one of the overloaded constructors in the base class – the one that takes two strings as parameters – is called with the “MyBase.New” code.   The string values of ‘first’ and ‘last’ are then assigned to the Person class constructor parameters ‘firstname’ and ‘lastname’.     You can reference any overloaded constructor in this way, depending on what you think may be useful to users of the ClubMember class.

A Constructor Variation

You're not limited to the basic example that I've shown here, of course.   You can and mix-and-match to create  variations of constructors to suit every need.  One common, useful approach is to use a parent class constructor, but then also add further functionality or information to it.  

Here’s an example of the kind of thing I mean.      Let’s say that it would be useful to have a ClubMember constructor that took in three key items of information – forename,  surname and date joined.    The first two elements are both already available via one of the base class overloaded constructors, as I've just demonstrated.   And we know that the DateJoined property is a member of the ClubMember class itself.

So, to create our ‘hybrid’ constructor is very easy.   First we set three parameters, one for each of those three properties I mentioned.  Then we call the base class constructor using MyBase and pass in the forename and surname variables.   Finally, we write an additional line which assigns the value of the third parameter “joined” to the DateJoined property.

 

 

This new constructor in the ClubMember class now allows you to create new instances of ClubMembers for which you can pass in the three parameters I've described above.  You can then create new instances of ClubMembers and assign values to forename, surname and date joined properties.

 

Summary

This short article only scratches the surface of inheritance. It's a large and often complicated topic.  But I hope that inthe context of the Chess Club project, you can see the basics of how it works.   In the next article, I'll do some more work with the ClubMember class.