Advertisement
7_2009-2012 Data Structures #221576

VB.NET OOPS (Object Oriented Programming) - A must read for any VB Programmer

This is a must read for every one interested in VB or VB.NET - and everyone who need to learn VB.NET. This article uncovers some basic Object Oriented Programming Features of Visual Basic.NET. The whole article is divided to 10 lessons. The source code for these lessons is provided with the article.

AI

AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Source Code
original-source
<h1> OOPS In VB.NET - A Practical Guide </h1>
<p>
You may download the article, and this html file and source code is included in the zip file.
<h2>Introduction</h2>
<p>VB.NET is completely Object Oriented. This article uncovers some basic Object
Oriented Programming Features of Visual Basic.NET. The whole article is divided to 10 lessons.
The source code for these lessons is provided with the article.</p>
<p>This tutorial is designed with the following 
objectives.</p>
<ol>
<li>To provide a sound knowledge about Object 
Oriented Programming in VB.NET 
<li>To educate how Object Oriented techniques 
are used in VB.NET 
<li>To explain the following concepts simply and easily. 
<ul>
<li>Creating And Using Classes And Objects In 
VB.NET 
<li>Encapsulation, Abstraction, Inheritance And 
Polymorphism 
<li>Overloading And Overriding 
<li>Constructors And Destructors 
<li>Static Functions </li></ul></li></ol>
<p>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 easily.</p>
<h2>Using the code</h2>
<p>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 excercises in this article. You can download it from the
Microsoft website. The VB.NET compiler (<b>vbc.exe</b>) normally resides in your
FrameworkSDK\bin folder.</p>
<p>To manually compile a source code file, you may use the command prompt to
type</p>
<p><code> vbc filename.vb /out:"filename.exe" /r:"System.Windows.Forms.dll","System.dll"</code></p>
<h2><id name= name="LESSON 1: NAMESPACES, CLASSES AND OBJECTS, MODULES">LESSON 1: NAMESPACES, CLASSES AND OBJECTS, MODULES</h2>
<h3>1) A Namespace</h3>
In VB.NET, classes and other data structures for a specific purpose are grouped together to form a namespace.You can use the classes in a namespace, by simply
importing the namespace.The 'imports' keyword is used to import a namespace to
your project..NET framework provides a rich set of built in classes, groupedto
various namespaces.In this lesson, we are using the system namespace.Import the
System namespace (already available in .NET)
<pre lang=vbnet>
Imports System
</pre>
<h3>2) A Class</h3>
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 allhuman beings. Dog is a class to represent all Dogs.Classes can
contain functions too.Animals is a namespace
<pre lang=vbnet>
Namespace Animals
</pre>
Dog is a class in the namespace Animals
<pre lang=vbnet>
Class Dog
</pre>
Bark is a function in this class
<pre lang=vbnet>
	Function Bark()
		Console.Writeline ("Dog is barking")
	End Function
End Class
End Namespace
</pre>
<h3>3) An Object</h3>
An object is an instance of a class. For example,Jimmy is an object of type Dog.
We will createan object in the next section. Read on.
<h3>4) Modules</h3>
You can use modules to write common functions. A module is agroup of functions.
Unlike functions in classes, public functionsin modules can be called directly
from some where else.VB provides Functions and Subroutines. Functions and
Subroutines are almost same, but subroutines can't returna value.
<pre lang=vbnet>
Public Module modMain
</pre>
Execution will start from the Main() subroutine
<pre lang=vbnet>
Sub Main()
		
	 'Call our function. See below
	 OurFunction()	
End sub
</pre>
OurFunction: Our own little function to use the class Dog
<pre lang=vbnet>
Function OurFunction()	
	 'Here is how we declare a variable Jimmy of type Dog.
	 'We use Animals.Dog because, the class Dog is in the
	 'namespace Animals (see above).
	
	 Dim Jimmy as Animals.Dog
	
	 'Create an object. Unlike in VB 6, it is not required to use
	 'the 'set' keyword.
	 	
	 Jimmy = new Animals.Dog()
	
	 'Another way to create an object is
	 'Dim Jimmy as new Dog
	
	 'Call Jimmy's Main Function 	
	 Jimmy.Bark()
	
End Function
End module
</pre>
<h2><id name= name="LESSON 2: ACCESS TYPES">LESSON 2: ACCESS TYPES</h2>
The major access types are Public, Private, Friend And Protected.A class may
contain functions, variables etc, either publicor 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 functionsinside the
class. Protected members are much like private members,but they have some
special use while inheriting the class. Wewill see this later, in Inheritance
(Lesson 5).Friend members can be accessed only from elements in thesame project,
and not by elements outer the current project.Let us expand our dog class.
<p>Import the System namespace (already available in .NET)</p>
<pre lang=vbnet>
Imports System
</pre>
Animals is a namespace
<pre lang=vbnet>
Namespace Animals
</pre>
Dog is a class in the namespace Animals
<pre lang=vbnet>
Public Class Dog
	'A public variable	
	Public AgeOfDog as Integer
</pre>
Bark is a function in this class. It is public
<pre lang=vbnet>
	Public Function Bark()
		Console.Writeline ("Dog is barking")
	End Function
	
</pre>
Walk is a function in this class. It is private
<pre lang=vbnet>
	Private Function Walk()
		Console.Writeline ("Dog is walking")
	End Function
	
End Class
End Namespace
</pre>
Our Module
<pre lang=vbnet>
Public Module modMain
</pre>
Execution will start from the Main() subroutine
<pre lang=vbnet>
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
</pre>
Additional Notes:
<h3>Encapsulation:</h3>
Putting all the data and related functions, in the class is calledas
Encapsulation.
<h3>Data Hiding or Abstraction:</h3>
Normally, in a class, variables used to hold data (like the age ofa dog) is
declared as private. Functions or property routines are usedto access these
variables. Protecting the data of an object fromouter functions is called as
Abstraction or Data Hiding. This prevents accidental modification of data by
functions outside the class.
<h2><id name= name="LESSON 3: SHARED FUNCTIONS">LESSON 3: SHARED FUNCTIONS</h2>
The shared members in a class (both functions and variables)can be used with out
creating objects of the class as shown.The Shared modifier indicates the method
does not operate on aspecific instance of a type and may be invoked directly
froma type rather than through a particular instance of a type.
<p>Import the System namespace (already available in .NET)</p>
<pre lang=vbnet>
Imports System
</pre>
Animals is a namespace
<pre lang=vbnet>
Namespace Animals
</pre>
Dog is a class in the namespace Animals
<pre lang=vbnet>
Class Dog
</pre>
Bark is a now a public, shared function in this class
<pre lang=vbnet>
	Public Shared Function Bark()
		Console.Writeline ("Dog is barking")
	End Function
	
	</pre>
Walk is a public function in this class. It is not shared
<pre lang=vbnet>
	Public Function Walk()
		Console.Writeline ("Dog is walking")
	End Function
	
End Class
End Namespace
</pre>
Our Module
<pre lang=vbnet>
Public Module modMain
</pre>
Execution will start from the Main() subroutine
<pre lang=vbnet>
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
</pre>
<h2><id name= name="LESSON 4: OVERLOADING">LESSON 4: OVERLOADING</h2>
Overloading is a simple technique, to enable a single function name to accept
parameters of different type.
<p>Let us see a simple Adder class</p>
Import the System namespace (already available in .NET)
<pre lang=vbnet>
Imports System
Class Adder
</pre>
Here, we have two Add() functions.This one adds two integers.Convert.ToString is
equivalent to good old Cstr
<pre lang=vbnet>
	Overloads Public Sub Add(A as Integer, B as Integer)
		Console.Writeline ("Adding Integers: " + Convert.ToString(a + b))
	End Sub
	
</pre>
This one adds two strings
<pre lang=vbnet>
	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
</pre>
<h2><id name= name="LESSON 5: INHERITANCE">LESSON 5: INHERITANCE</h2>
Inheritance is the property in which, a derived classaquires 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. 
<p>Let us see a simple example.</p>
Import the System namespace (already available in .NET)
<pre lang=vbnet>
Imports System
</pre>
<h3>Our simple base class</h3>
<pre lang=vbnet>
Class Human
	'This is something that all humans do
	Public Sub Walk()
		Console.Writeline ("Walking")
	End Sub
		
End Class
</pre>
<h3>Now, let us derive a class from human</h3>
A programmer IS_A Human
<pre lang=vbnet>
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
</pre>
Just a main class
<pre lang=vbnet>
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
</pre>
Additional Notes:
<p><i>MustInherit</i>: The MustInherit keyword specifies that a class cannotbe
instantiated and can be used only as a base class.i.e, if you declare our Human
class as 'MustInherit Class Human' ,then you can't create object of type Human
with out inheriting it.</p>
<p><i>NotInheritable</i>: The NotInheritable keyword specifies that a class
cannotbe inherited. I.e, if you specify 'NotInheritable Class Human', noderived
classes can be made from Human class</p>
<h2><id name= name="LESSON 6: OVERRIDING">LESSON 6: OVERRIDING</h2>
By default, a derived class inherits methods from its base class. If an
inherited property or method needs to behave differently inthe derived class it
can be overridden; that is, you can define anew 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 functionis
overriding some base class function.Let us see an example
<p>Import the System namespace (already available in .NET)</p>
<pre lang=vbnet>
Imports System
</pre>
<h3>Our simple base class</h3>
<pre lang=vbnet>
Class Human
	'Speak() is declared Overridable
	Overridable Public Sub Speak()
		Console.Writeline ("Speaking")
	End Sub
		
End Class
</pre>
<h3>Now, let us derive a class from human</h3>
An Indian IS_A Human
<pre lang=vbnet>
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
</pre>
<p> 
<h3>Just a class to put our Main()</h3>
<pre lang=vbnet>
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
</pre>
<h2><id name= name="LESSON 7: POLYMORPHISM">LESSON 7: POLYMORPHISM</h2>
Polymorphism is the property in which a single object can take more than one
forms. 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 derved 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 <i>speak() </i>in your base class. You derived a child
class from your base class and overloaded the function speak(). Then, you
created a child class object and assigned it to a base class variable. Now, if
you call 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, the speak() function in
base class will work. This is acheived through run time type identification of
objects.  See the example. 
<p> Import the System namespace (already available in .NET)</p>
<pre lang=vbnet>
Imports System
</pre>
This example is exactly the same one we saw in previous lesson.The only
difference is in the Shared Sub Main() in class MainClass. So scroll down.Let us
see an example
<h3>Our simple base class</h3>
<pre lang=vbnet>
Class Human
	'Speak() is declared Overridable
	Overridable Public Sub Speak()
		Console.Writeline ("Speaking")
	End Sub
		
End Class
</pre>
<h3>Now, let us derive a class from human</h3>
An Indian IS_A Human
<pre lang=vbnet>
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
</pre>
<h3>Carefully examine the code in Main()</h3>
<pre lang=vbnet>
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
</pre>
<h2><id name= name="LESSON 8: CONSTRUCTORS & DESTRUCTORS">LESSON 8: CONSTRUCTORS & DESTRUCTORS</h2>
Import the System namespace (already available in .NET)
<pre lang=vbnet>
Imports System
</pre>
A Constructor is a special function, which is calledautomatically when a class
is created. In VB.NET, you should useNew() to create constructors as in the
below examples.Constructors can be overloaded (see Lesson 4), but unlikein
functions, the Overloads keyword is not required.A Destructor is a special
function, which is calledautomatically when a class is Destroyed. In VB.NET, you
should useFinalize() routine to create Destructors.They are similiar to
Class_Initialize and Class_Terminatein VB 6.0
<p>Dog is a class</p>
<pre lang=vbnet>
Class Dog
	'The age variable
	Private Age as integer
	
</pre>
The Default Constructor.
<pre lang=vbnet>
	Public Sub New()
		Console.Writeline ("Dog is Created With Age Zero")
		Age=0
	End Sub
</pre>
The Parameterized Constructor
<pre lang=vbnet>
	Public Sub New(val as Integer)
		Console.Writeline ("Dog is Created With Age " + Convert.ToString(val))
		Age=val
	End Sub
</pre>
This is the destructor.
<pre lang=vbnet>
	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
</pre>
<h2><id name= name="LESSON 9: PROPERTY ROUTINES">LESSON 9: PROPERTY ROUTINES</h2>
You can use both properties and fields to store information in an object.
Whereas fields are simply public variables, properties use property proceduresto
control how values are set or returned.You can use the Get/Set keywords for
getting/setting properties.See the following example.
<p>Import the System namespace (already available in .NET)</p>
<pre lang=vbnet>
Imports System
</pre>
Dog is a class
<pre lang=vbnet>
Public Class Dog
	'A private variable	to hold the value
	Private mAgeOfDog as Integer
</pre>
This is our property routine<pre lang=vbnet>
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
</pre>
<h3>Another Class</h3>
<pre lang=vbnet>
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
</pre>
<h2><id name= name="LESSON 10: A SIMPLE PROGRAM">LESSON 10: A SIMPLE PROGRAM</h2>
Let us analyze a simple program. First, let us import required namespaces
<pre lang=vbnet>
Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing
</pre>
<pre lang=vbnet>
	'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()
</pre>
Set the text property of this class. We inheritedthis property from the base
class.
<pre lang=vbnet>
Me.Text = "Hello, How Are You?"
End Sub
End Class
</pre>
<pre lang=vbnet>
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
</pre>
<p> 
<h2>History</h2>
<p>Nov 13,2004 - Prepared this article for publishing
Original Comments (3)
Recovered from Wayback Machine