Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  A Practical Introduction to OOP. Part 1 - You ARE an OOP Programmer!
A Practical Introduction to OOP. Part 1 - You ARE an OOP Programmer!
by Mike McIntyre | Published  01/22/2004 | .NET Newbie | Rating:
Mike McIntyre

I am a system architect, developer, and project manager for aZ Software Developers, LLP.

I feel very lucky because my work at aZ Software Developers allows me the time to be an active mentor, trainer, and coach in the Microsoft .NET technical community.

DevCity is my favorite community site. Click to see my DevCity profile -> Mike McIntyre

 

 

View all articles by Mike McIntyre...
A Practical Introduction to OOP. Part 1 - You ARE an OOP Programmer!

Updated: 01/22/2004

Article source code: practical_oop_1.zip

Requirements:

  • Any edition of Visual Studio.NET 2002 or 2003
  • Entry level VB.NET skills.

Introduction

Have you used the last few versions of VB.OLD? - You ARE an OOP Programmer!

Have you tried the Hello World! example in .NET? - You ARE an OOP Programmer!

It is impossible to do any programming with Microsoft. NET without using object-oriented programming (OOP). Though you may not have yet written classes of your own and used them to create objects - you have created objects from the classes of the .NET Framework and used the objects in your applications.

Using Objects is OOP

Consider the code below. It declares a variable for use with a specific data type. It uses a class constructor to instantiate an object. It assigns an object's reference to a variable. It assigns a value to an object property. It calls an object method to perform an action.

    ' Declare a variable named aButton for use with a Button data type.
    Dim aButton As Button

    ' Use the Button class' New Button() constructor to instantiate
    ' (create) a Button object.
    ' Assign the Button object's reference to the aButton variable.
    aButton = New Button()

    ' Set the Visible property of the Button object to True.
    aButton.Visible = True

    ' Call the BringToFront method of the Button object.
    aButton.BringToFront()

Have you done similar things with the .NET Button class? Have you used another .NET class to create a TextBox object, a ListBox object, a Label object, or another .NET form control object? Have you created and used a Form object?

If so - You are an OOP Programmer!

If so, why do you have trouble using other more complex classes from the .NET Framework? Why do you find it hard to code classes of your own? Why does .NET seem so complex and intimidating? Why can't you create the nifty user control you have in mind? WHY DO YOU KEEP GETTING THE ERROR "An unhandled exception of type 'System.NullReferenceException' occurred"?

Why? It is because you need to expand your OOP programming skills. Microsoft®.NET raises the bar on what you need to know about OOP to be a good VB.NET programmer. The simple use of objects learned using previous versions of Visual Basic and the simple things you have learned to do with VB.NET is not enough to master OOP programming with the .NET Framework Class Library or to create powerful objects of your own.

There is good news. It is not hard to increase your OOP programming skills. You need to learn a just a few new concepts, study some examples, and put what you learn to work.

The Concepts

Listed below are the concepts covered in this three part article. The concepts are grouped and ordered as they will appear in the article

Part One

  • Computer Memory, Application Memory, Stack, Heap, Variable
  • Data Type, Value Type, Reference Type, Type Declaration, Class, Object
  • Class Member, Field, Property, Method, Event

Part Two

  • Constructors
  • Destructors

Part Three

  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

These are very powerful concepts. Master these concepts and you will be well on the way to becoming a full-fledged OOP programmer.

Computer Memory, Application Memory, Stack, Heap, Variable

Computer Memory is the electronic holding place for instructions and data that your computer's microprocessor can reach quickly. When your computer is in normal operation, its memory usually contains the main parts of the operating system and some application programs and related data that are being used. Memory is distinguished from storage; storage is a medium that holds the much larger amounts of data that won't fit into RAM and may not be immediately needed there. A database is a good example of storage, as is a file on a hard disk.

Application Memory is the portion of a computer's memory allocated by the Windows operating system to a running application. Application Memory consists of two memory locations; 1) the stack and; 2) the heap.

Application Memory

 Stack

Heap

The stack and the heap are the two locations in application memory that must kept in mind as OOP is performed.

A variable is a named location in memory. You declare a variable to set aside a location in memory, give it a name, and define the type of data that can be used with the variable.

Data Type, Value Type, Reference Type, Class, Object

A data type is a set of values from which a variable may take its value. Examples of data types are Integer, String, Boolean, Button, Textbox, and Form.

    'Declare a variable named myInteger of data type Integer.
    Dim myInteger As Integer

    'Declare a variable named aButton of data type Button.
    Dim aButton As Button

Data types are categorized as either a value type or a reference type. Below are some examples of data types from each category.

Value Type Data Types - Byte, Integer, Single, Double, Boolean, Char, Struct, Enum

Reference Type Data Types - Array, Button, Form, Collection, DataSet, Font

The category of a data type determines how it will be contained in memory.

Value Type - A variable declared as a data type from the value type category is structured in memory to directly contain a value.

    'An Integer is a data type which is categorized as a value type.
    ' Declare a variable named myInteger of data type Integer.
    Dim myInteger As Integer
    'Assign the value 1 to the myInteger variable.
    myInteger = 1

After running the code above the result is a variable in memory named myInteger that directly contains the value 1.

Application Memory

 Stack

Heap

myInteger

1

 

Reference Type - A variable declared as a data type from the reference type category is structured to contain a reference to an actual object in the heap, not the actual object.  A reference is a number that is a memory address where an object exists in the heap.

    'A Button is data type which is categorized as a reference type.
    'Declare a variable named myButton of data type Button.
    Dim myButton As Button

After running the code above the result is a variable in memory named myButton that can contain a reference to button object in the heap. AT THIS POINT THE VALUE OF THE myButton VARIABLE IS NULL.

Application Memory

 Stack

Heap

myButton

NULL

 

    'Create a new Button object in the heap and assign its reference
    'to the aButton variable.
    myButton = New Button()

After running the code above the myButton variable contains a reference to a button object in the heap. The reference is an integer which is the address where the button object begins in the heap. In the example 12034511 is the address of the button object in the heap.

Application Memory

 Stack

Heap

myButton

12034511

12034511

button object

Note: You may hear other programmers refer to a reference as a pointer. In .NET the proper term is reference. .NET documentation and error messages use the word reference as you will see in the next section.

A Common Error

Have you seen this error?

The error message says:

An unhandled exception of "System.NullReferenceException" occurred ...

Additional information: Object reference not set to an instance of an object.

This error occurs when an attempt is made to use a reference type variable which has been declared but has not been assigned a reference to an actual object. The variable contains a NullReference. The last line of code below will raise the NullReferenceException error.

    'Declare a variable named myButton of data type Button.
    Dim myButton As Button
    'Attempt to set the BackColor property of using the abutton variable.
    myButton.BackColor = Color.Blue

The first line of code declares myButton as a reference type variable that can contain a reference to a button object.

The last line of code attempts to use myButton before it has been assigned a reference to a button object. When the last line attempts to change the BackColor property using the myButton variable, this is what exists in memory:

Application Memory

 Stack

Heap

myButton

NULL

 

The interpreter can not find a reference to a button object in the myButton variable so it throws a System.NullReferenceException. There is a NULL (Nothing) value stored in the myButton variable instead of a reference to a button object in the heap.

Before the myButton variable can be used a button object must be assigned to it. A new button could be created and assigned to myButton OR an existing button could be assigned to myButton.

To correct the problem, code is added to create a new Button object and assign its reference to the myButton variable:

    'Declare a variable named myButton of type Button
    Dim myButton As Button
    'ADDED: Create a new Button object in the heap 
    'and assign its reference to the aButton variable.
    myButton = New Button()
    'Change the BackColor property of the button object
    'referenced by the myButton variable.
    myButton.BackColor = Color.Blue

Now when the last line of code executes, the myButton variable references a button object in heap memory. The BackColor of the object will be changed to Blue.

Application Memory

 Stack

Heap

myButton

12034511

12034511

button object

Class Member, Field, Property, Method, Event

In the code examples earlier in this article, how did .NET know how to create a new Button object? How did it know what parts and pieces make up a button object?

.NET used the Button class to instantiate (create) a Button object in the heap. In object-oriented programming, you instantiate a class to create an object, a concrete instance of the class. 

A class is code that defines a structure which can be used to instantiate an object in memory. The .NET compiler uses class code as a template to create a real thing - an object - in an application's heap memory.

There are thousands of classes in the .NET Framework. Each class defines a structure you can use as a building block for your application. There are classes to instantiate objects that serve as form controls, data structures, drawing tools, data providers, and many more.

To understand how to use the .NET Framework class' building blocks and to author your own powerful classes you must learn more about class statements.

A class statement declares: the name of a class and the variables, properties, events, and methods that comprise the class. A sample class statement is shown below.

Friend Class LogOnHelper

    Private _UserName As String = ""

    Friend Property UserName() As String
        Get
            Return _UserName
        End Get
        Set(ByVal Value As String)
            _UserName = Value
        End Set
    End Property

    Event Authorized()
    Event Rejected()

    Friend Sub VerifyUserName(ByVal CurrentUser As String)
        If _UserName = CurrentUser Then
            RaiseEvent Authorized()
        Else
            RaiseEvent Rejected()
        End If
    End Sub

End Class

The variables, properties, events, and methods in a class statement are called class members. Class members are the code ingredients that define the structure of a class.

The class members of each of the thousands of classes in the .NET Framework Class Library are documented in the Visual Studio.NET help system. Knowing how to locate a class members topic in .NET Help is absolutely necessary for putting the .NET Framework Classes to best use.

To see how important a class member topic can be to your programming efforts please take a moment to examine the Button Members topic in .NET Help. Search VisualStudio.NET Help using "Button Members" as the search string. Please print the Button Members topic for use with this article. Note: I used the Visual Basic and Related help filter when I found the topics for this article.

Examine the Button Members topic you have printed. For now focus on the Public Properties, Public Methods, and Public event sections. These three sections document the Public members of the Button class - the members available when a Button object is deployed in program code.

Field and Property Members

Properties and Fields represent information stored in an object. Properties and Fields are defined by Field and Property statements within a class statement.

Field members are not shown in .NET class members topics. Field members are private variables within the class. If a programmer using a class is allowed to change and/or read the value of a field member within a class, a Property member will be included in the class. A Property member will provides controlled access to the field member.

The values of an object's Fields and Properties are set and retrieved by the programmer using assignment statements the same way variables are set and retrieved. Examine the Public Properties section of the Button Members help topic. Find the BackColor property. According to the help topic, the BackColor of a button object is used to set or get the BackColor of a Button.

    'Set the BackColor Property of a Button
    aButton.BackColor = Color.Blue

    'Get the BackColor Property of a Button
    MessageBox.Show(aButton.BackColor.ToString)

Behind the BackColor property in the class statement there is a private Field variable that stores the BackColor value. The set statement above changes the value of the Field. The get statement above retrieves the value of the field.

Method Member

Methods represent actions an object can be called to take. Methods are defined by subroutine and function statements within a class statement.

An object's methods are called by the programmer like subroutines or functions.

Examine the Public Methods section of the Button Members .NET help topic. Find the Hide method. According to the help topic, the Hide method of a Button object is used to conceal the Button object from the end user.

    'Hide a Button.
    aButton.Hide()

In the Button class there is a public method named Hide. At runtime the statement above will call the Hide method for a button object in the heap referenced by a variable named aButton.

Event Member

Events represent notifications an object can broadcast. Events are defined in Event and RaiseEvent statements within a class statement.

Examine the Public Events section of the Button Members help topic. Find the Click event. According to the help topic the Click event is raised when the Button object is clicked. A handler can be included in program code that responds to a button object's Click event.

Review

In part one of this article the concepts below have been covered:

  • Computer Memory, Application Memory, Stack, Heap, Variable
  • Data Type, Value Type, Reference Type, Type Declaration, Class, Object
  • Class Member, Field, Property, Method, Event

To review what you have learned please download, decompress, and open the YouAreAnOppProgrammer project linked to this article.

In the project is a class called LogOnHelper. This LogOnHelper class is defined using class members as described in the article. Examine the class statement in the LogOnHelp.vb file.

You may find it useful to open two copies of the project, one to examine the code and one to run so you can see the application in action.

Examine the code in the LogOnForm.vb file to see how the LogOnHelper class is instantiated and the resulting LogOnHelper object is used.

As you review the LogOnHelper class and the LogOnForm class notice how the concepts covered in this article are put to use in the sample project.

A LogOnHelper Members topic is provided below.

Class Name: LogOnHelper

Members:

Public Properties

Name Description
UserName Gets or sets the name of an authorized user.

Public Methods

Name Description
VerifyUserName Verifies the name provided by a user matches the authorized user name.

Public Events

Name Description
Authorized Occurs when the user name provided by a user matches the authorized user name.
Rejected Occurs when the user name provided by a user does NOT match the authorized user name.
How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:4.26356589147288 out of 5
 129 people have rated this page
Article Score39122
Sponsored Links