Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  OOP Basics - Constructors
OOP Basics - Constructors
by Ged Mead | Published  08/01/2009 | .NET Newbie | Rating:
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.


View all articles by Ged Mead...
Introduction to Constructors


In the previous Part, I created four fields and four corresponding properties in the Person class. These, you will remember, represent items of information about a class instance - that is an instance of a Person that we create. So far though we don't have the means to create such an instance.

If you find some of the terms confusing - creating a class instance, object instances, declaring a Person instance and so on - don't worry. It will all make sense in time.

In everyday terms, an instance of a Person class object is simply something that represents a real person - you, me, the chess club secretary, whoever.

And at some point we will want to be able to create a new instance of a Person object so that we can actually do something useful with it - add it to our membership list, check its date of birth, change its surname on marriage, etc.

You will already have created new instances of objects many times using the VB.NET built-in classes. Just to take a couple at random, a Point object and a Form object, for example:

Code Copy
    Dim pt As New Point(12, 25)
    Dim frm1 As New Form1

Although I'm sure you will have typed the words "As New" countless times, I wonder if you have ever really thought about what happens when you type "New Point" or "New Form1" as in the examples. Perhaps not. Why would you? The Microsoft developers who created the Point and Form Classes built in all the functionality you need (well, as much as they thought you would need!).

With the Person Class though, we do have to decide what action needs to be taken when code such as the following is written:-

Code Copy

    Dim Person1 As New Person

What Is A Constructor?

When the keyword New is used in the way it is shown in the two examples above, the Constructor for that class will be called. A Constructor is another specialised procedure which is called once whenever client code, such as that in the two examples above, runs. It is the code which creates a new instance of a Person object. It will instantiate those four fields that we designed earlier and it will assign the default values to them.

When the Person constructor runs, a New instance of a Person object will be created. At the moment of creation (in our example so far), that Person instance will have the values of "Not Known", "Anonymous", 1900, 1, 1 and "Not Known" assigned to the four fields. Milliseconds later those values may change, but - for now - that is the situation.

The above example code snippet will create a Person instance and make it available in memory. It will initially be given the default settings for the fields of this type of object. That is, the instance will be created and the fields will be initialized with those values.

Let's look at some examples of constructors, starting with the easiest version.

Default Constructor
The Constructor is a procedure which is always given the name "New".

Code Copy

    Sub New()

    End Sub

The most basic Constructor will contain only one line:

Code Copy
    Sub New()
    End Sub

If you have looked at classes which have been created by other developers, you might have noticed that they don't seem to contain a basic Sub New like the one shown above. The reason for this is that, rather confusingly, if you omit to include one yourself, Visual Basic will automatically create one for you.

As a matter of good practice - at least in the early stages of your OOP work - I recommend that you include this basic Constructor in all of your Classes. Later in these articles, you will see what that line actually does and what it means.

Creating An Instance
The constructor shown above will be called any time that you put a line of code such as this one in your project:

Code Copy
    Dim Person1 As New Person

and a new Person instance will be created. You can see this relationship in the diagram below:


As I explained in the introduction to constructors earlier, at the moment of instantiation (the point in time when the new instance of the Person class is created), the fields of the class are initialized (that is, they are given their initial values).
So, in the Person Class as we currently have it coded, this would be the state:

1.    Person1's m_forename field will have a value of "Not Known"
2.    Person1's m_surname field will have a value of "Anonymous"
3.    Person1's m_dateofbirth field will have a value of 1900, 1, 1
4.    Person1's m_gender field will have a value of "Not Known"

I hope that's clear, because it is quite important to understand that this instance - Person1 - now physically exists in memory and has those initial values assigned to those four fields.

What About Properties and Constructors?
In the cash dispenser analogy that I used earlier, the properties acted as an interface with the user, a means by which stored information (in the field) was funnelled in and out. Properties are transient and dynamic. They simply act as devices to carry data from and to clients.

Therefore the Forename, Surname, DateOfBirth and Gender Properties are not given values to store. When client code needs to know the forename of a Person instance, it will be allowed to access the Forename property.

The Forename property is linked behind the scenes to the m_forename field, which does hold data. The value in the m_forename field is passed to the Forename property. Refer back to the Forename Property Procedure in the previous article to see how this is done. The client is informed what that value is by reading what it is passed via the Forename property.

Testing the Default Constructor
We can add code to the Form in the demo project to create a new instance of the Person class and display some details.

Create Demo Controls:
This small code sample will demonstrate how to create an instance of the Person class. It will use the default constructor, so the values in the four fields will be the default values.

You will also see that Intellisense will allow the client code to select any of the four properties, but not any of the four fields.

In the Class Basics project, open up the Designer window and add a button and a label to the form.

Code the Button Click .
Now double click on the button to open up the code window and the code for the button's click event. Enter this code in the button click event:

Code Copy

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Create a new Person Instance
        Dim TestPerson As New Person
    End Sub

Hopefully, as soon as you typed the word "New" and began to type the word "Person", you will have seen that Intellisense kicked in and displayed the dropdown list in the usual way. However, as the screenshot below shows, the Person type is now also included in the Intellisense listing:


View the Default Values
By adding a little more code to the Button Click event, we can check that those default values have really been set:

Code Copy
        '  Retrieve default values
        Label1.Text = TestPerson.Forename & " " & TestPerson.Surname

You should see the following when you run the project and click the button:


The default values are shown via the Forename and Surname Properties.  And, as you can see, those two default initial values have been passed from the Private Fields to the client via the Public Properties.

If you think back to the property procedure I created earlier, you will realise that what we have done here is to invoke the Get sub blocks for each of those Properties.

In a real application, we won't want to be limited to those default values, so let's change some of them now. The way we change those is via Set sub block of the Property Procedure.

Setting a Value
We can change values stored in m_forename, m_surname, etc from client code by Setting the value of the Forename and Surname Properties. As before, the client code can only tinker with the Properties; it doesn't get to play with the fields directly. Replace the code in the Button Click event with the following:

Code Copy

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' Create a new Person Instance
        Dim TestPerson As New Person

        '  Assign values
        TestPerson.Forename = "Johnnie"
        TestPerson.Surname = "Smith"

        '  Display values
        Label1.Text = TestPerson.Forename & " " & TestPerson.Surname

    End Sub

Run the project and click the Button and you should see:

I could of course have changed any of the values. I selected just those two for demonstration purposes.

Sponsored Links