Object Oriented Programming in VB PDF
Object Oriented Programming in VB PDF
ObjectOrientedProgrammingInVB.NETCodeProject
Contents
Introduction
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
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:
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.
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
1/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
A Class
Probably, you are already familiar with classes and objects. Simply speaking, a Class is a definition of a real life
object. For example, Human is a class for representing all human beings. Dog is a class to represent all Dogs.
Classes can contain functions too. Animals is a namespace.
NamespaceAnimals
An Object
An object is an instance of a Class. For example, Jimmy is an object of type Dog. We will create an object in the
next section. Read on.
Modules
You can use modules to write common functions. A Module is a group of functions. Unlike functions in classes,
Public functions in modules can be called directly from anywhere else. VB provides Functions and
Subroutines. Functions and Subroutines are almost the same, but the difference is that a subroutine can't return
a value.
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
2/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
PublicModulemodMain
Execution will start from the Main() subroutine:
SubMain()
'Callourfunction.Seebelow
OurFunction()
Endsub
DimJimmyasAnimals.Dog
'Createanobject.UnlikeinVB6,itisnotrequiredtouse
'the'set'keyword.
Jimmy=newAnimals.Dog()
'Anotherwaytocreateanobjectis
'DimJimmyasnewDog
'CallJimmy'sMainFunction
Jimmy.Bark()
EndFunction
Endmodule
Animals is a namespace.
NamespaceAnimals
3/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
Additional Notes:
Encapsulation
Putting all the data and related functions in a Class is called Encapsulation.
Animals is a namespace.
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
4/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
NamespaceAnimals
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.
ImportsSystem
ClassAdder
Here, we have two Add() functions. This one adds two integers. Convert.ToString is equivalent to the good old
CStr.
OverloadsPublicSubAdd(AasInteger,BasInteger)
Console.Writeline("AddingIntegers:"+Convert.ToString(a+b))
EndSub
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
5/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
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.
ImportsSystem
Our simple base class:
ClassHuman
'Thisissomethingthatallhumansdo
PublicSubWalk()
Console.Writeline("Walking")
EndSub
EndClass
Now, let us derive a class from Human.
A Programmer is a Human.
ClassProgrammer
InheritsHuman
'WealreadyhavetheaboveWalk()function
'Thisissomethingthatallprogrammersdo;)
PublicSubStealCode()
Console.Writeline("Stealingcode")
EndSub
EndClass
Just a MainClass.
ClassMainClass
'Ourmainfunction
SharedSubMain()
DimTomasProgrammer
Tom=newProgrammer
'Thiscallisokiebecauseprogrammergotthisfunction
'fromitsbaseclass
Tom.Walk()
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
6/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
'ThisisalsocorrectbecauseTomisaprogrammer
Tom.StealCode()
EndSub
EndClass
Additional Notes:
MustInherit
The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class. I.e.,
if you declare our Human class as "MustInheritClassHuman", then you can't create objects of type
Human without inheriting it.
NotInheritable
The NotInheritable keyword specifies that a class cannot be inherited. I.e., if you specify
'NotInheritableClassHuman', no derived classes can be made from the Human class.
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.
ImportsSystem
Our simple base class:
ClassHuman
'Speak()isdeclaredOverridable
OverridablePublicSubSpeak()
Console.Writeline("Speaking")
EndSub
EndClass
Now, let us derive a class from Human:
An Indian is a Human:
ClassIndian
InheritsHuman
'LetusmakeIndianspeakHindi,theNationalLanguage
'inIndia
'Speak()isoverridingSpeak()initsbaseclass(Human)
OverridesPublicSubSpeak()
Console.Writeline("SpeakingHindi")
'Important:Asyouexpect,anycalltoSpeak()insidethisclass
'willinvoketheSpeak()inthisclass.Ifyouneedto
'callSpeak()inbaseclass,youcanuseMyBasekeyword.
'Likethis
'Mybase.Speak()
EndSub
EndClass
Just a class to put our Main().
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
7/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
ClassMainClass
'Ourmainfunction
SharedSubMain()
'TomisagenericHuman
DimTomasHuman
Tom=newHuman
'TonyisahumanandanIndian
DimTonyasIndian
Tony=newIndian
'ThiscallwillinvoketheSpeak()function
'inclassHuman
Tom.Speak()
'ThiscallwillinvoketheSpeak()function
'inclassIndian
Tony.Speak()
EndSub
EndClass
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.
ImportsSystem
This example is exactly the same as the one we saw in the previous lesson. The only difference is in the SharedSub
Main() in the class MainClass. So scroll down and see an example:
Our simple base class:
ClassHuman
'Speak()isdeclaredOverridable
OverridablePublicSubSpeak()
Console.Writeline("Speaking")
EndSub
EndClass
Now, let us derive a class from Human.
An Indian is a Human.
ClassIndian
InheritsHuman
'LetusmakeIndianspeakHindi,theNationalLanguage
'inIndia
'Speak()isoverridingSpeak()initsbaseclass(Human)
OverridesPublicSubSpeak()
Console.Writeline("SpeakingHindi")
'Important:Asyouexpect,anycalltoSpeak()insidethisclass
'willinvoketheSpeak()inthisclass.Ifyouneedto
'callSpeak()inbaseclass,youcanuseMyBasekeyword.
'Likethis
'Mybase.Speak()
EndSub
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
8/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
EndClass
Carefully examine the code in Main():
ClassMainClass
'Ourmainfunction
SharedSubMain()
'LetusdefineTomasahuman(baseclass)
DimTomasHuman
'Now,IamassiginganIndian(derivedclass)
Tom=newIndian
'Theaboveassignmentislegal,because
'IndianIS_Ahuman.
'Now,letmecallSpeakas
Tom.Speak()
'WhichSpeak()willwork?TheSpeak()inIndian,orthe
'Speak()inhuman?
'Thequestionarisesbecause,TomisdeclaredasaHuman,
'butanobjectoftypeIndianisassignedtoTom.
'TheAnsweris,theSpeak()inIndianwillwork.Thisisbecause,
'mostobjectorientedlanguageslikeVb.netcanautomatically
'detectthetypeoftheobjectassignedtoabaseclassvariable.
'ThisiscalledPolymorphism
EndSub
EndClass
Dog is a class:
ClassDog
'Theagevariable
PrivateAgeasinteger
The default constructor:
PublicSubNew()
Console.Writeline("DogisCreatedWithAgeZero")
Age=0
EndSub
The parameterized constructor:
PublicSubNew(valasInteger)
Console.Writeline("DogisCreatedWithAge"+Convert.ToString(val))
Age=val
EndSub
This is the destructor:
OverridesProtectedSubFinalize()
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
9/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
Console.Writeline("DogisDestroyed")
EndSub
'TheMainFunction
SharedSubMain()
DimJimmy,JackyasDog
'Createtheobjects
'Thiswillcallthedefaultconstructor
Jimmy=newDog
'Thiswillcalltheparameterizedconstructor
Jacky=newDog(10)
EndSub
'TheDestructionwillbedoneautomatically,when
'theprogramends.ThisisdonebytheGarbage
'Collector.
EndClass
Dog is a class.
PublicClassDog
'Aprivatevariabletoholdthevalue
PrivatemAgeOfDogasInteger
This is our property routine:
PublicPropertyAge()AsInteger
'Calledwhensomeonetriestoretreivethevalue
Get
Console.Writeline("GettingProperty")
ReturnmAgeOfdog
EndGet
Set(ByValValueAsInteger)
'Calledwhensomeonetriestoassignavalue
Console.Writeline("SettingProperty")
mAgeOfDog=Value
EndSet
EndProperty
EndClass
Another class:
ClassMainClass
'Ourmainfunction.Executionstartshere.
SharedSubMain()
'Letuscreateanobject.
DimJimmyasDog
Jimmy=newDog
'Wecan'taccessmAgeofDogdirectly,soweshould
'useAge()propertyroutine.
'Setit.TheAgeSetroutinewillwork
Jimmy.Age=30
'Getitback.TheAgeGEtroutinewillwork
DimcurAge=Jimmy.Age()
EndSub
EndClass
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
10/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
'PassthisobjecttotheRun()functiontostart
System.Windows.Forms.Application.Run(sf)
EndSub
EndClass
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
Nov 13th, 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. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Share
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
11/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
Anoop Madhusudanan
Architect
India
Architect, Developer, Speaker | Wannabe GUT inventor & Data Scientist | Microsoft MVP in C# | Tweets on JS, Mobile, C#,
.NET, Cloud, Hadoop | Seeker.
Follow: I'm In Twitter @amazedsaint | Blog: http://amazedsaint.com
BigData for .NET Developers Using Azure & Hadoop
Hack Raspberry Pi to Build Apps In C#, Winforms and ASP.NET
Changing Times For Web Developers Responsive Design and 6 Tips You Need To Survive
7 Freely Available Ebooks For .NET developers
5 Back to Basics C# Articles Fluent Interfaces, Expr Trees etc
3 Gems from Mono to spice up your .NET Apps
Top 5 Common Mistakes .NET Developers Must Avoid
6 Cool VS2010 Tips you may find interesting
4 .NET 4.0 Libraries you *should* know about
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
12/13
14/04/2016
ObjectOrientedProgrammingInVB.NETCodeProject
Seleccionar idioma
http://www.codeproject.com/Articles/8825/ObjectOrientedProgrammingInVBNET?display=Print
13/13