Click here to Skip to main content
Email Password   helpLost your password?

Contents

Introduction

VB.NET is completely object oriented. This article uncovers some basic Object Oriented Programming features of Visual Basic. NET. The whole article is divided into ten lessons. The source code for these lessons is provided with the article.

This tutorial is designed with the following objectives:

  1. To provide a sound knowledge about Object Oriented Programming in VB.NET.
  2. To educate how Object Oriented techniques are used in VB.NET.
  3. To explain the following concepts in an easy and simple way:

Go through this tutorial and you will start making sense of almost any .NET code. Also, Java/CPP programmers can use this to understand OOPs in VB.NET.

Using the code

The source code for each lesson is available as a .vb source code file. You need Microsoft .NET framework SDK installed in your system to compile and execute the exercises in this article. You can download it from the Microsoft website. The VB.NET compiler (vbc.exe) normally resides in your FrameworkSDK\bin folder.

To manually compile a source code file, you may use the command prompt to type: vbc filename.vb /out:"filename.exe" /r:"System.Windows.Forms.dll","System.dll"

Lesson 1: Namespaces, Classes & Objects, Modules

Lesson 2: Access Types

The major access types are Public, Private, Friend and Protected. A Class may contain functions, variables etc., which can be either Public or Private or Protected or Friend. If they are Public, they can be accessed by creating objects of the Class. Private and Protected members can be accessed only by the functions inside the Class. Protected members are much like Private members, but they have some special use while inheriting a Class. We will see this later, in Inheritance (Lesson 5). Friend members can be accessed only by elements of the same project, and not by the ones outside the current project. Let us expand our dog class.

Import the System namespace (already available in .NET).

Imports System

Animals is a namespace.

Namespace Animals

Dog is a class in the namespace Animals.

Public Class Dog
    'A public variable    

    Public AgeOfDog as Integer

Bark is a function in this class. It is Public:

    Public Function Bark()
        Console.Writeline ("Dog is barking")
    End Function

Walk is a function in this class. It is Private.

    Private Function Walk()
        Console.Writeline ("Dog is walking")
    End Function
End Class
End Namespace

Our Module:

Public Module modMain

Execution will start from the Main() subroutine:

Sub Main()
       'Call our function. See below

       OurFunction()    
End sub
    'OurFunction: Called from Main()

    Function OurFunction()
        Dim Jimmy as Animals.Dog
        Jimmy=new Animals.Dog()
        'This will work, because Bark & Ageofdog are public

        Jimmy.Bark
        Jimmy.AgeOfDog=10
         'Calling the Walk function will not work here, because

        'Walk() is outside the class Dog        

        'So this is wrong. Uncomment this and try to compile, it will

        'cause an error.

        'Jimmy.Walk

    End Function        
End Module

Additional Notes:

Lesson 3: Shared Functions

The shared members in a class (both functions and variables) can be used without creating objects of a class as shown. The Shared modifier indicates that the method does not operate on a specific instance of a type and may be invoked directly from a type rather than through a particular instance of a type.

Import the System namespace (already available in .NET).

Imports System

Animals is a namespace.

Namespace Animals

Dog is a class in the namespace Animals.

Class Dog

Bark is a now a Public, shared function in this class.

    Public Shared Function Bark()
        Console.Writeline ("Dog is barking")
    End Function

Walk is a Public function in this class. It is not shared.

    Public Function Walk()
        Console.Writeline ("Dog is walking")
    End Function
End Class
End Namespace

Our Module:

Public Module modMain

Execution will start from the Main() subroutine.

Sub Main()
        'We can call the Bark() function directly,

        'with out creating an object of type Dog -

        'because it is shared.

        Animals.Dog.Bark()
        'We can call the Walk() function only

        'after creating an object, because

        'it is not shared.

        Dim Jimmy as Animals.Dog
        Jimmy=new Animals.Dog()
        Jimmy.Walk()
        'Now Guess? The WriteLine() function we used so far

        'is a shared function in class Console :)

        'Also, we can write the Main() function itself as a shared

        'function in a class. i.e Shared Sub Main(). Try

        'moving Main() from this module to the above class

End sub
End Module

Lesson 4: Overloading

Overloading is a simple technique, to enable a single function name to accept parameters of different type. Let us see a simple Adder class. Import the System namespace (already available in .NET).

Imports System
Class Adder

Here, we have two Add() functions. This one adds two integers. Convert.ToString is equivalent to the good old CStr.

    Overloads Public Sub Add(A as Integer, B as Integer)
        Console.Writeline ("Adding Integers: " + Convert.ToString(a + b))
    End Sub

This one adds two strings.

    Overloads Public Sub Add(A as String, B as String)
        Console.Writeline ("Adding Strings: " + a + b)
    End Sub
    'And both have the same name. This is possible because, we used the

    'Overloads keyword, to overload them.

    'Here, we have the Main Function with in this class. When you write.

    'your main function inside the class, it should be a shared function.

    Shared Sub Main()
        Dim AdderObj as Adder
        'Create the object

        AdderObj=new Adder
        'This will invoke first function

        AdderObj.Add(10,20)
        'This will invoke second function

        AdderObj.Add("hello"," how are you")
    End Sub
End Class

Lesson 5: Inheritance

Inheritance is the property in which, a derived class acquires the attributes of its base class. In simple terms, you can create or 'inherit' your own class (derived class), using an existing class (base class). You can use the Inherits keyword for this.

Let us see a simple example. Import the System namespace (already available in .NET).

Imports System

Our simple base class:

Class Human
    'This is something that all humans do

    Public Sub Walk()
        Console.Writeline ("Walking")
    End Sub
End Class

Now, let us derive a class from Human.

A Programmer is a Human.

Class Programmer
    Inherits Human
    'We already have the above Walk() function

    'This is something that all programmers do ;)

    Public Sub StealCode()
        Console.Writeline ("Stealing code")
    End Sub
End Class

Just a MainClass.

Class MainClass
    'Our main function

    Shared Sub Main()
        Dim Tom as Programmer
        Tom=new Programmer
        
        'This call is okie because programmer got this function

        'from its base class

        Tom.Walk()
        
        'This is also correct because Tom is a programmer

        Tom.StealCode()
    End Sub
End Class

Additional Notes:

Lesson 6: Overriding

By default, a derived class Inherits methods from its base class. If an inherited property or method needs to behave differently in the derived class it can be overridden; that is, you can define a new implementation of the method in the derived class. The Overridable keyword is used to mark a function as overridable. The keyword Overrides is used to mark that a function is overriding some base class function. Let us see an example.

Import the System namespace (already available in .NET).

Imports System

Our simple base class:

Class Human
    'Speak() is declared Overridable

    Overridable Public Sub Speak()
        Console.Writeline ("Speaking")
    End Sub
End Class

Now, let us derive a class from Human:

An Indian is a Human:

Class Indian
    Inherits Human
    'Let us make Indian speak Hindi, the National Language

    'in India

    'Speak() is overriding Speak() in its base class (Human)

    Overrides Public Sub Speak()
        Console.Writeline ("Speaking Hindi")
    'Important: As you expect, any call to Speak() inside this class

    'will invoke the Speak() in this class. If you need to

    'call Speak() in base class, you can use MyBase keyword.

    'Like this

    'Mybase.Speak()

    End Sub
End Class

Just a class to put our Main().

Class MainClass
    'Our main function

    Shared Sub Main()
        'Tom is a generic Human

        Dim Tom as Human
        Tom=new Human
        'Tony is a human and an Indian

        Dim Tony as Indian
        Tony=new Indian
        'This call will invoke the Speak() function

        'in class Human

        Tom.Speak()
        'This call will invoke the Speak() function

        'in class Indian

        Tony.Speak()
    End Sub
End Class

Lesson 7: Polymorphism

Polymorphism is the property in which a single object can take more than one form. For example, if you have a base class named Human, an object of Human type can be used to hold an object of any of its derived type. When you call a function in your object, the system will automatically determine the type of the object to call the appropriate function. For example, let us assume that you have a function named speak() in your base class. You derived a child class from your base class and overloaded the function speak(). Then, you create a child class object and assign it to a base class variable. Now, if you call the speak() function using the base class variable, the speak() function defined in your child class will work. On the contrary, if you are assigning an object of the base class to the base class variable, then the speak() function in the base class will work. This is achieved through runtime type identification of objects. See the example.

Import the System namespace (already available in .NET).

Imports System

This example is exactly the same as the one we saw in the previous lesson. The only difference is in the Shared Sub Main() in the class MainClass. So scroll down and see an example:

Our simple base class:

Class Human
    'Speak() is declared Overridable

    Overridable Public Sub Speak()
        Console.Writeline ("Speaking")
    End Sub
End Class

Now, let us derive a class from Human.

An Indian is a Human.

Class Indian
    Inherits Human
    'Let us make Indian speak Hindi, the National Language

    'in India

    'Speak() is overriding Speak() in its base class (Human)

    Overrides Public Sub Speak()
        Console.Writeline ("Speaking Hindi")
    'Important: As you expect, any call to Speak() inside this class

    'will invoke the Speak() in this class. If you need to

    'call Speak() in base class, you can use MyBase keyword.

    'Like this

    'Mybase.Speak()

    End Sub
End Class

Carefully examine the code in Main():

Class MainClass
    'Our main function

    Shared Sub Main()
        'Let us define Tom as a human (base class)

        Dim Tom as Human
        'Now, I am assiging an Indian (derived class)

        Tom=new Indian
        'The above assignment is legal, because

        'Indian IS_A human.

        'Now, let me call Speak as

        Tom.Speak()
        'Which Speak() will work? The Speak() in Indian, or the

        'Speak() in human?

        'The question arises because, Tom is declared as a Human,

        'but an object of type Indian is assigned to Tom.

        'The Answer is, the Speak() in Indian will work. This is because,

        'most object oriented languages like Vb.net can automatically

        'detect the type of the object assigned to a base class variable.

        'This is called Polymorphism

    End Sub
End Class

Lesson 8: Constructors & Destructors

Import the System namespace (already available in .NET).

Imports System

A Constructor is a special function which is called automatically when a class is created. In VB.NET, you should use useNew() to create constructors. Constructors can be overloaded (see Lesson 4), but unlike the functions, the Overloads keyword is not required. A Destructor is a special function which is called automatically when a class is destroyed. In VB.NET, you should use useFinalize() routine to create Destructors. They are similar to Class_Initialize and Class_Terminate in VB 6.0.

Dog is a class:

Class Dog
    'The age variable

    Private Age as integer

The default constructor:

    Public Sub New()
        Console.Writeline ("Dog is Created With Age Zero")
        Age=0
    End Sub

The parameterized constructor:

    Public Sub New(val as Integer)
        Console.Writeline ("Dog is Created With Age " + Convert.ToString(val))
        Age=val
    End Sub

This is the destructor:

    Overrides Protected Sub Finalize()
        Console.Writeline ("Dog is Destroyed")
    End Sub
    'The Main Function

    Shared Sub Main()
        Dim Jimmy, Jacky as Dog
        'Create the objects

        'This will call the default constructor

        Jimmy=new Dog
        'This will call the parameterized constructor

        Jacky=new Dog(10)
    End Sub
    'The Destruction will be done automatically, when

    'the program ends. This is done by the Garbage

    'Collector.

End Class

Lesson 9: Property Routines

You can use both properties and fields to store information in an object. While fields are simply Public variables, properties use property procedures to control how values are set or returned. You can use the Get/Set keywords for getting/setting properties. See the following example. Import the System namespace (already available in .NET).

Imports System

Dog is a class.

Public Class Dog
    'A private variable    to hold the value

    Private mAgeOfDog as Integer

This is our property routine:

Public Property Age() As Integer
    'Called when someone tries to retreive the value

Get
    Console.Writeline ("Getting Property")
    Return mAgeOfdog
End Get
Set(ByVal Value As Integer)
    'Called when someone tries to assign a value     

    Console.Writeline ("Setting Property")
    mAgeOfDog=Value
End Set
End Property
End Class

Another class:

Class MainClass
    'Our main function. Execution starts here.

    Shared Sub Main()
    'Let us create an object.

    Dim Jimmy as Dog
    Jimmy=new Dog        
    'We can't access mAgeofDog directly, so we should

    'use Age() property routine.

    'Set it. The Age Set routine will work

    Jimmy.Age=30
    'Get it back. The Age GEt routine will work

    Dim curAge=Jimmy.Age()
    End Sub
End Class

Lesson 10: A simple program

Let us analyze a simple program. First, let us import the required namespaces:

Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing
    'We are inheriting a class named SimpleForm, from the

    'class System.Windows.Forms.Form

    '

    'i.e, Windows is a namespace in system, Forms is a

    'namespace in Windows, and Form is a class in Forms.

Public Class SimpleForm
Inherits System.Windows.Forms.Form
        'Our constructor

Public Sub New()
    'This will invoke the constructor of the base

    'class

MyBase.New()

Set the text property of this class. We inherited this property from the base class:

Me.Text = "Hello, How Are You?"
End Sub
End Class
Public Class MainClass
    Shared Sub Main()
        'Create an object from our SimpleForm class

        Dim sf as SimpleForm
        sf=new SimpleForm
        
        'Pass this object to the Run() function to start

         System.Windows.Forms.Application.Run(sf)
    End Sub
End Class

That is it. Now you can atleast read and understand most of those VB.NET source code, and probably implement more OOP features in your VB.NET programs. Now, in my next article, I'll try to cover the patterns and practices in VB.NET.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralThank's ......
Member 4057475
12:40 14 Mar '09  
Thanks Alot Thumbs Up now I understand it that was very nice and easy 5 / 5 Smile
GeneralOOP in vb.net (database)
tornado12
15:20 8 Feb '09  
Hi every one
I have lot difficulties in OOP in vb.net when I wan to use classes to connect my application
to data base and if you can help me I wan a sample application (Add,delete,modify…).
Please I need help I have an exam in OOP but the problem is that I don’t have any idea about
OOP when we use database
GeneralIt is very useful
hafizes
8:57 6 Nov '08  
Thanks
General[Message Removed]
hankjmatt
22:10 13 Oct '08  
Spam message removed
GeneralNice Article
naman
1:53 28 May '08  
Nice article. you have cleared all the difficult topics in a proper go & proper explanation is there in the same regard

Thanks
Smile

NaMaN

GeneralThanks
jomet
21:38 2 Mar '08  
nice article!!!
Laugh
GeneralNeed a Programming Refresher? Read This Article!
suzmonster
6:08 14 Dec '07  
I've been away from programming for a couple years. I'm only halfway through this article and must say it is EXACTLY what I needed. I wish I would have found this article two months ago. I'm currently refactoring a VB6 program over to .NET in Visual Studio 2005. I understand OOP, SQL, and RDBMS but I had lost touch with the "lingo" of exactly what is what in a program. Thank you for breaking .NET down for me so I can quickly get back up to speed! Cool
Generalnice one mate
waqas rafi
17:10 5 Oct '07  
well iam new to the vb world and find it really interesting and in short span we can grasp many things from this contribution.....

cheers


no matter what
JUST KEEP IT REAL!

Generalnice one mate
waqas rafi
17:09 5 Oct '07  
well iam new to the vb world and find it really interesting and in short span we can grasp many things from this contribution.....

cheers

no matter what

JUST KEEP IT REAL!

GeneralHey....you rocks...nice job
theGreco
6:39 21 Sep '07  
this have been the best way to explain about oop to anybody...congratulations.

News"vb .net" and oops
jay_dubal
3:22 27 Jun '07  
"vb .net" and oops
http://www.free-ebooks-download.org

DOWNLOAD VB.NET ASP.NET MCTS MCPD AJAX ADO.NET C# EBOOKS
Generalhow can I test the code??
Sahar Diab
6:25 31 May '07  
hi oop>>>
I wondered if u can help me in testing the code and give me the steps to test the class....
I am new in vb.net and in dealing with dll files
any help appretiated....
thx ,


Sahar
GeneralThanks!
turtle1010
23:53 9 Feb '07  
Thank you so much for the lessons, they are extremly simply written but up to the pointSmile
GeneralFor a fresher...... it's the best.
Manuuuuu
8:34 19 Dec '06  
Simple and understanding words and memorable samples....good, Best of luck and moreover thanks.

Viju
Generalvery simple but very informative
percyvimal
4:04 19 Dec '06  
Very simple article but very informative and covers lot of hard to understand features in a very simpler easily understandable way.

Expect more such nice articles
Regards


Help in need is the help indeed

GeneralThank You...
Woofs
11:04 15 Sep '06  

Thank you for the article. I found it to be very clear and concise. Perfect examples. Smile
GeneralGreat Contribution!!
Raish
22:59 9 Aug '06  
I think this article tells a lot of than a book of 1,000 pages related to OOP.
Specially lesson related to Polymorphism excellent.
Laugh

Raishul Islam
Generalsit back and enjoy
f2
21:46 20 May '06  
http://download.microsoft.com/download/6/2/4/6247616D-A0C7-4552-B622-3F0450DE2462/06VB1.wmv

from,
-= aLbert =-

GeneralThe Walk() function is inside the class Dog
MickYL
21:30 12 Apr '06  
Sub Main()
'Call our function. See below
OurFunction()
End sub


Really great Article. Just wanted to say I think the Walk() function is declared a private function within the Class Dog. How do you use such a private member ? Really learnt a lot on through this article. Thanks.

'OurFunction: Called from Main()
Function OurFunction()
Dim Jimmy as Animals.Dog
Jimmy=new Animals.Dog()
'This will work, because Bark & Ageofdog are public
Jimmy.Bark
Jimmy.AgeOfDog=10
'Calling the Walk function will not work here, because
'Walk() is outside the class Dog
'So this is wrong. Uncomment this and try to compile, it will
'cause an error.
'Jimmy.Walk
End Function
End Module
GeneralOO Programming concepts VB.NET
Integrale EVO2
16:09 28 Mar '06  
Many thanks, at last I see the light. I've been struggling for weeks with various articles and pages from books trying to put together some basic no frills document to try to have definitions and a reference for these concepts.

This was and is a fantastic artical for beginners. Straight and to the point. .NET is now not so much of a mystery.

Again many thanks.

Will NZ
GeneralNicely done
GlimmerMan
11:57 21 Mar '06  
One of the things I enjoy doing is writing very easy to understand tutorials as you have done here, nicely done and simple as it should be.;)

Kevin S. Gallagher
Programming is an art form that fights back
NewsFrench Translation
Xoh
22:00 9 Nov '05  
With the kind authorization of his author, this article has been translated in french. You can read it here : http://xo.developpez.com/tutoriel/vb.net/poo/

Thanks Anoop Wink

__
Xo

-- modified at 17:32 Sunday 13th November, 2005


Last Updated 19 Nov 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010