You are on page 1of 13


Object Oriented Programming In VB.NET ­ CodeProject

Object Oriented Programming In VB.NET
Anoop Madhusudanan, 19 Nov 2004
   4.15 ﴾138 votes﴿
A must read for anyone who is interested in VB.NET. This article uncovers some basic Object Oriented Programming
features of Visual Basic .NET. The whole article is divided into 10 lessons. The source code for these lessons is provided with
the article.

Download source files ‐ 10.7 Kb

Using the code
Lesson 1: Namespaces, Classes & Modules
Lesson 2: Access Types
Lesson 3: Shared Functions
Lesson 4: Overloading
Lesson 5: Inheritance
Lesson 6: Overriding
Lesson 7: Polymorphism
Lesson 8: Constructors & Destructors
Lesson 9: Property Routines
Lesson 10: A Simple Application

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:
Creating and using classes and objects in VB.NET.
Encapsulation, Abstraction, Inheritance and Polymorphism.
Overloading and Overriding.
Constructors and Destructors.
Static functions.
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.­Oriented­Programming­In­VB­NET?display=Print


Classes & Objects.exe" /r:"System.vb source code file.NET framework SDK installed in your system to compile and execute the exercises in this article. http://www.exe﴿ normally resides in your FrameworkSDK\bin folder. .NET framework provides a rich set of built in­Oriented­Programming­In­VB­NET?display=Print 2/13 .dll". Import the System namespace ﴾already available in ."System. by simply importing the namespace. A Module is a group of functions. Human is a class for representing all human beings. Modules You can use modules to write common functions. In this lesson. We will create an object in the next section.Forms. Simply speaking. Public functions in modules can be called directly from anywhere else. You can download it from the Microsoft website. You can use the classes in a namespace. The Imports keyword is used to import a namespace to your project.NET ­ CodeProject Using the code The source code for each lesson is available as a . The VB. you are already familiar with classes and objects. a Class is a definition of a real life object. Classes can contain functions too. Unlike functions in classes.Windows.14/04/2016 Object Oriented Programming In VB. Jimmy is an object of type Dog. Animals is a namespace. Dog is a class to represent all Dogs. Imports System A Class Probably.Writeline ("Dog is barking")      End Function  End Class  End Namespace An Object An object is an instance of a Class. Modules A Namespace In VB.NET﴿.NET compiler ﴾vbc. For example. Namespace Animals Dog is a class in the namespace Animals: Class Dog Bark is a function in this Class:     Function Bark()          Console. you may use the command prompt to type: vbc filename. VB provides Functions and Subroutines.dll" Lesson 1: Namespaces.NET. classes and other data structures for a specific purpose are grouped together to form a namespace.codeproject. You need Microsoft . grouped together to various namespaces. we are using the System namespace. For example. Functions and Subroutines are almost the same. To manually compile a source code file.vb /out:"filename. Read on. but the difference is that a subroutine can't return a value.

Protected members are much like Private members. If they are Public. See below         OurFunction()      End sub OurFunction: Our own little function to use the class Dog: Function OurFunction()             'Here is how we declare a variable Jimmy of type Dog.codeproject. We will see this later. in Inheritance ﴾Lesson 5﴿.com/Articles/8825/Object­Oriented­Programming­In­VB­NET?display=Print 3/13 . Friend and Protected.NET﴿. Imports System Animals is a namespace. but they have some special use while inheriting a Class.Dog               'Create an object. and not by the ones outside the current project.Bark()  End Function  End module Lesson 2: Access Types The major access types are Public. Let us expand our dog class. Import the System namespace ﴾already available in .                      Jimmy = new Animals. Private and Protected members can be accessed only by the functions inside the Class. Public Class Dog      'A public variable          Public AgeOfDog as Integer Bark is a function in this class. Unlike in VB 6. it is not required to use         'the 'set' keyword.               Dim Jimmy as Animals.         'We use Animals. It is Public: Public Function Bark()      Console.Dog()               'Another way to create an object is         'Dim Jimmy as new Dog               'Call Jimmy's Main Function              Jimmy. they can be accessed by creating objects of the Class. Friend members can be accessed only by elements of the same project.Writeline ("Dog is barking")  End Function  http://www.14/04/2016 Object Oriented Programming In VB..NET ­ CodeProject Public Module modMain Execution will start from the Main() subroutine: Sub Main()         'Call our function. variables etc. the class Dog is in the         'namespace Animals (see above). Private. A Class may contain functions. which can be either Public or Private or Protected or Friend.Dog because. Namespace Animals Dog is a class in the namespace Animals.

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. because          'Walk() is outside the class Dog                  'So this is­Oriented­Programming­In­VB­NET?display=Print 4/13 . in a Class. 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.codeproject. See below         OurFunction()      End sub      'OurFunction: Called from Main()      Function OurFunction()          Dim Jimmy as Animals. http://www. variables used to hold data ﴾like the age of a dog﴿ is declared as Private.NET﴿.NET ­ CodeProject Walk is a function in this class.          'Jimmy.     Private Function Walk()          Console.AgeOfDog=10           'Calling the Walk function will not work here.14/04/2016 Object Oriented Programming In VB. Imports System Animals is a namespace.Bark          Jimmy. Functions or property routines are used to access these variables.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.Dog          Jimmy=new Animals. Uncomment this and try to compile. Data Hiding or Abstraction: Normally.Walk      End Function          End Module Additional Notes: Encapsulation Putting all the data and related functions in a Class is called Encapsulation. It is Private. Import the System namespace ﴾already available in . Protecting the data of an object from outside functions is called Abstraction or Data Hiding. This prevents accidental modification of data by functions outside the class.Dog()          'This will work. because Bark & Ageofdog are public          Jimmy. it will          'cause an error.

Convert. Class Dog Bark is a now a Public.14/04/2016 Object Oriented Programming In VB.Bark()          'We can call the Walk() function only          'after creating an object. we have two Add() functions.Dog()          Jimmy. Public Shared Function Bark()      Console. we can write the Main() function itself as a shared          'function in a class.Writeline ("Adding Integers: " + Convert. 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. Imports System  Class Adder Here.          Dim Jimmy as Animals.codeproject.ToString is equivalent to the good old CStr.Walk()          'Now Guess? The WriteLine() function we used so far          'is a shared function in class Console :)          'Also.ToString(a + b))  End Sub  http://www. Sub Main()          'We can call the Bark() function directly. Import the System namespace ﴾already available in .Writeline ("Dog is walking")      End Function  End Class  End Namespace Our Module: Public Module modMain Execution will start from the Main() subroutine. This one adds two integers. Let us see a simple Adder class. shared function in this class.Dog.NET﴿.     Public Function Walk()          Console.e Shared Sub Main().Dog          Jimmy=new Animals.          'with out creating an object of type Dog ‐          'because it is shared.          Animals. i. because          'it is not shared.Writeline ("Dog is barking")  End Function  Walk is a Public function in this class. It is not­Oriented­Programming­In­VB­NET?display=Print 5/13 .NET ­ CodeProject Namespace Animals Dog is a class in the namespace Animals. Overloads Public Sub Add(A as Integer. B as Integer)      Console.

using an existing class ﴾base class﴿. 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. Let us see a simple example.      'Here. Import the System namespace ﴾already available in . it should be a shared function.Walk()  http://www.      Shared Sub Main()          Dim AdderObj as Adder          'Create the object          AdderObj=new Adder          'This will invoke first function          AdderObj.)      Public Sub StealCode()­Oriented­Programming­In­VB­NET?display=Print 6/13 . This is possible because.     Overloads Public Sub Add(A as String. we used the      'Overloads keyword.Add(10. Imports System Our simple base class: Class Human      'This is something that all humans do      Public Sub Walk()          Console.Add("hello". a derived class acquires the attributes of its base class. to overload them." how are you")      End Sub  End Class Lesson 5: Inheritance Inheritance is the property in which.      'your main function inside the class.14/04/2016 Object Oriented Programming In VB. You can use the Inherits keyword for this. Class Programmer      Inherits Human      'We already have the above Walk() function      'This is something that all programmers do .NET﴿.NET ­ CodeProject This one adds two strings. A Programmer is a Human. When you write. B as String)          Console.codeproject.Writeline ("Stealing code")      End Sub  End Class Just a MainClass.Writeline ("Walking")      End Sub  End Class Now. In simple terms. you can create or 'inherit' your own class ﴾derived class﴿. we have the Main Function with in this class.20)          'This will invoke second function          AdderObj.Writeline ("Adding Strings: " + a + b)      End Sub      'And both have the same name. let us derive a class from Human.

I. a derived class Inherits methods from its base class.. that is. any call to Speak() inside this class      'will invoke the Speak() in this class. Imports System Our simple base class: Class Human      'Speak() is declared Overridable      Overridable Public Sub Speak()          Console.Writeline ("Speaking Hindi")      'Important: As you expect. then you can't create objects of type Human without inheriting it. you can define a new implementation of the method in the derived class.codeproject. let us derive a class from Human: An Indian is a Human: Class Indian      Inherits Human      'Let us make Indian speak Hindi. http://www. NotInheritable The NotInheritable keyword specifies that a class cannot be inherited. If you need to      'call Speak() in base class.      'Like this      'Mybase.Speak()      End Sub  End Class Just a class to put our Main().StealCode()      End Sub  End Class Additional Notes: MustInherit The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class. Import the System namespace ﴾already available in . If an inherited property or method needs to behave differently in the derived class it can be overridden.NET﴿.NET ­ CodeProject                   'This is also correct because Tom is a programmer­Oriented­Programming­In­VB­NET?display=Print 7/13 . you can use MyBase keyword.e.e. The Overridable keyword is used to mark a function as overridable. I. if you declare our Human class as "MustInherit Class Human". the National Language      'in India      'Speak() is overriding Speak() in its base class (Human)      Overrides Public Sub Speak()          Console. Let us see an example.14/04/2016 Object Oriented Programming In VB. if you specify 'NotInheritable Class Human'. Lesson 6: Overriding By default.. no derived classes can be made from the Human class. The keyword Overrides is used to mark that a function is overriding some base class function.Writeline ("Speaking")      End Sub  End Class Now.

you create a child class object and assign it to a base class variable. Now. Then.NET ­ CodeProject 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()      End Sub  http://www. Imports System This example is exactly the same as the one we saw in the previous lesson. if you are assigning an object of the base class to the base class variable.14/04/2016 Object Oriented Programming In VB.NET﴿. Class Indian      Inherits Human      'Let us make Indian speak Hindi. You derived a child class from your base class and overloaded the function speak(). then the speak() function in the base class will work. For example. Import the System namespace ﴾already available in . let us assume that you have a function named speak() in your base class. the system will automatically determine the type of the object to call the appropriate function. if you call the speak() function using the base class variable.Speak()      End Sub  End Class Lesson 7: Polymorphism Polymorphism is the property in which a single object can take more than one form. The only difference is in the Shared Sub Main() in the class MainClass. When you call a function in your object. An Indian is a Human. So scroll down and see an example: Our simple base class: Class Human      'Speak() is declared Overridable      Overridable Public Sub Speak()          Console. any call to Speak() inside this class      'will invoke the Speak() in this class. the National Language      'in India      'Speak() is overriding Speak() in its base class (Human)      Overrides Public Sub Speak()          Console. For example.Writeline ("Speaking")      End Sub  End Class Now. On the contrary. This is achieved through runtime type identification of objects. If you need to      'call Speak() in base class. if you have a base class named Human. you can use MyBase­Oriented­Programming­In­VB­NET?display=Print 8/13 . an object of Human type can be used to hold an object of any of its derived type. the speak() function defined in your child class will work. let us derive a class from Human.Writeline ("Speaking Hindi")      'Important: As you expect.      'Like this      'Mybase.Speak()          'This call will invoke the Speak() function          'in class Indian          Tony.codeproject. See the example.

 This is because.          'This is called Polymorphism      End Sub  End Class Lesson 8: Constructors & Destructors Import the System namespace ﴾already available in . let me call Speak as          Tom.          'most object oriented languages like Vb.NET.          'Now.0.ToString(val))      Age=val  End Sub  This is the destructor:     Overrides Protected Sub Finalize()  http://www.codeproject.14/04/2016 Object Oriented Programming In VB. In VB.NET﴿ can automatically          'detect the type of the object assigned to a base class variable.Speak()          'Which Speak() will work? The Speak() in Indian. Dog is a class: Class Dog      'The age variable      Private Age as integer The default constructor: Public Sub New()      Console. the Speak() in Indian will­Oriented­Programming­In­VB­NET?display=Print 9/13 . you should use useFinalize() routine to create Destructors.NET ­ CodeProject 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. A Destructor is a special function which is called automatically when a class is destroyed. the Overloads keyword is not required. because          'Indian IS_A human.          'The Answer is. Tom is declared as a Human. I am assiging an Indian (derived class)          Tom=new Indian          'The above assignment is legal.          'but an object of type Indian is assigned to Tom. Constructors can be overloaded ﴾see Lesson 4﴿.Writeline ("Dog is Created With Age " + Convert. but unlike the functions. or the          'Speak() in human?          'The question arises because. They are similar to Class_Initialize and Class_Terminate in VB 6.Writeline ("Dog is Created With Age Zero")      Age=0  End Sub  The parameterized constructor: Public Sub New(val as Integer)      Console. In VB. Imports System A Constructor is a special function which is called automatically when a class is created. you should use useNew() to create constructors.

 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. See the following example.      Dim Jimmy as Dog      Jimmy=new Dog              'We can't access mAgeofDog directly. Execution starts here.NET﴿. You can use the Get/Set keywords for getting/setting properties.14/04/2016 Object Oriented Programming In VB.      'Set it. when      'the program ends. While fields are simply Public variables. so we should      'use Age() property routine.Writeline ("Getting Property")      Return mAgeOfdog  End Get  Set(ByVal Value As Integer)      'Called when someone tries to assign a value           Console.NET ­ CodeProject         Console.Writeline ("Dog is Destroyed")      End Sub      'The Main Function      Shared Sub Main()          Dim Jimmy. Import the System namespace ﴾already available in . properties use property procedures to control how values are set or returned.Age=30      'Get it back. Imports System Dog is a class.  End Class Lesson 9: Property Routines You can use both properties and fields to store information in an object.      Shared Sub Main()      'Let us create an object. 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 ("Setting Property")      mAgeOfDog=Value  End Set  End Property  End Class Another class: Class MainClass      'Our main­Oriented­Programming­In­VB­NET?display=Print 10/13 . The Age Set routine will work      Jimmy. The Age GEt routine will work      Dim curAge=Jimmy. This is done by the Garbage      'Collector.codeproject.Age()      End Sub  End Class http://www.

let us import the required namespaces: Imports System  Imports System.NET programs.Forms.NET source code.  Public Class SimpleForm  Inherits System. I'll try to cover the patterns and practices in VB. Now you can atleast read and understand most of those VB. 2004 Prepared this article for publishing. License This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves.Run(sf)      End Sub  End Class That is it. Windows is a namespace in system.NET. Forms is a      'namespace in Windows.Drawing      'We are inheriting a class named SimpleForm.Form      '      'i.ComponentModel  Imports System.codeproject.e.Windows.Forms.Windows. in my next article.Forms  Imports System. A list of licenses authors might use can be found here Share http://www.New() Set the text property of this class.Text = "Hello. and Form is a class in Forms. from the      'class System. First.Form          'Our constructor  Public Sub New()      'This will invoke the constructor of the base      'class  MyBase. 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. Now.Forms.Windows.NET ­ CodeProject Lesson 10: A simple program Let us analyze a simple­Oriented­Programming­In­VB­NET?display=Print 11/13 . If in doubt please contact the author via the discussion board below.Application.Windows. and probably implement more OOP features in your VB.14/04/2016 Object Oriented Programming In VB. History Nov 13th. We inherited this property from the base class: Me.

Developer.codeproject. Mobile. Speaker | Wannabe GUT inventor & Data Scientist | Microsoft MVP in C# | Tweets on JS.. Winforms and ASP. Follow: I'm In Twitter @amazedsaint | Blog: http://amazedsaint.NET 4. C#.0 Libraries you *should* know about You may also be interested in.NET Apps Top 5 Common Mistakes .14/04/2016 Object Oriented Programming In VB. Expr Trees etc 3 Gems from Mono to spice up your .NET ­ CodeProject About the Author Anoop Madhusudanan Architect India Architect.NET Developers Must Avoid 6 Cool VS2010 Tips you may find interesting 4 .NET Changing Times For Web Developers ‐ Responsive Design and 6 Tips You Need To Survive 7 Freely Available Ebooks For .com BigData for .. Hadoop | Seeker.NET Developers Using Azure & Hadoop Hack Raspberry Pi to Build Apps In C#. .com/Articles/8825/Object­Oriented­Programming­In­VB­NET?display=Print 12/13 . Cloud. Perl Object Oriented Programming Optimize SharePoint Storage with BLOB Externalization Introduction to Object Oriented Programming Concepts ﴾OOP﴿ and More SAPrefs ‐ Netscape‐like Preferences Dialog http://www.NET developers 5 Back to Basics C# Articles ‐ Fluent Interfaces.NET.

14/04/2016 Object Oriented Programming In VB.codeproject. Permalink | Advertise | Privacy | Terms of Use | Mobile Web02 |‐Oriented‐ Programming‐In‐VB‐NET to post and view comments on this article.160413.8.codeproject. or click here to get a print view with messages. 1999‐2016 http://www.1 | Last Updated 19 Nov 2004 Seleccionar idioma ▼ Article Copyright 2004 by Anoop Madhusudanan Everything else Copyright © CodeProject.NET ­ CodeProject Object Oriented Programming with C++ Window Tabs ﴾WndTabs﴿ Add‐In for DevStudio Comments and Discussions 52 messages have been posted for this article Visit­Oriented­Programming­In­VB­NET?display=Print 13/13 .