Contents
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:
- To provide a sound knowledge about Object Oriented Programming in VB.NET.
- To educate how Object Oriented techniques are used in VB.NET.
- 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.
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"
-
A Namespace
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, grouped together to various namespaces. In this lesson, we are using the System
namespace. Import the System
namespace (already available in .NET).
Imports System
-
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.
Namespace Animals
Dog
is a class in the namespace Animals
:
Class Dog
Bark
is a function in this Class
:
Function Bark()
Console.Writeline ("Dog is barking")
End Function
End Class
End Namespace
-
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 Function
s and Subroutines. Function
s and Subroutines are almost the same, but the difference is that a subroutine can't return a value.
Public Module modMain
Execution will start from the Main()
subroutine:
Sub Main()
OurFunction()
End sub
OurFunction
: Our own little function to use the class Dog
:
Function OurFunction()
Dim Jimmy as Animals.Dog
Jimmy = new Animals.Dog()
Jimmy.Bark()
End Function
End module
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
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()
OurFunction()
End sub
Function OurFunction()
Dim Jimmy as Animals.Dog
Jimmy=new Animals.Dog()
Jimmy.Bark
Jimmy.AgeOfDog=10
End Function
End Module
Additional Notes:
-
Encapsulation
Putting all the data and related functions in a Class
is called Encapsulation.
-
Data Hiding or Abstraction:
Normally, in a Class
, variables used to hold data (like the age of a dog) is declared as Private
. Functions or property routines are used to access these variables. 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.
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()
Animals.Dog.Bark()
Dim Jimmy as Animals.Dog
Jimmy=new Animals.Dog()
Jimmy.Walk()
End sub
End Module
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
Shared Sub Main()
Dim AdderObj as Adder
AdderObj=new Adder
AdderObj.Add(10,20)
AdderObj.Add("hello"," how are you")
End Sub
End Class
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
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
Public Sub StealCode()
Console.Writeline ("Stealing code")
End Sub
End Class
Just a MainClass
.
Class MainClass
Shared Sub Main()
Dim Tom as Programmer
Tom=new Programmer
Tom.Walk()
Tom.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. I.e., if you declare our Human
class as "MustInherit Class Human
", 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 'NotInheritable Class Human
', no derived classes can be made from the Human
class.
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
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
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")
End Sub
End Class
Just a class to put our Main()
.
Class MainClass
Shared Sub Main()
Dim Tom as Human
Tom=new Human
Dim Tony as Indian
Tony=new Indian
Tom.Speak()
Tony.Speak()
End Sub
End Class
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
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
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")
End Sub
End Class
Carefully examine the code in Main()
:
Class MainClass
Shared Sub Main()
Dim Tom as Human
Tom=new Indian
Tom.Speak()
End Sub
End Class
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
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
Shared Sub Main()
Dim Jimmy, Jacky as Dog
Jimmy=new Dog
Jacky=new Dog(10)
End Sub
End Class
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
Private mAgeOfDog as Integer
This is our property routine:
Public Property Age() As Integer
Get
Console.Writeline ("Getting Property")
Return mAgeOfdog
End Get
Set(ByVal Value As Integer)
Console.Writeline ("Setting Property")
mAgeOfDog=Value
End Set
End Property
End Class
Another class:
Class MainClass
Shared Sub Main()
Dim Jimmy as Dog
Jimmy=new Dog
Jimmy.Age=30
Dim curAge=Jimmy.Age()
End Sub
End Class
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
Public Class SimpleForm
Inherits System.Windows.Forms.Form
Public Sub New()
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()
Dim sf as SimpleForm
sf=new SimpleForm
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
- Nov 13th, 2004
- Prepared this article for publishing.