Unit Iii
Unit Iii
Example:
Module Module1
Sub Main()
Dim obj As New Subtr
obj.min()
End Sub
Public Class Subtr
Dim a As Integer = 100
Dim b As Integer = 10
Sub min()
Console.WriteLine("Subtraction of 100-10::" & a - b)
Console.ReadLine()
End Sub
End Class
End Module
Result:
Subtraction of 100-10::90
In the above example,obj is an instance of the class Subtr.Using this object the
function min is used without writing any code.
Fields, Properties, Methods, and Events
Fields, Properties, Methods, and Events are called the members of a class.
Inside the class, members are declared as either Public, Private, Protected,
Friend, or Protected Friend:
Public— Gives variables public access, which means there are no
restrictions on their accessibility.
Private— Gives variables private access, which means they are accessible
only from within their class, including any nested procedures.
Protected— Gives variables protected access, which means they are
accessible only from within their own class or from a class derived from that
class. Note that you can use Protected only at class level (which means you
can't use it inside a procedure), because you use it to declare members of a
class.
Friend— Gives variables friend access, which means they are accessible
from within the program that contains their declaration, as well as anywhere
else in the same assembly.
Protected Friend— Gives variables both protected and friend access, which
means they can be used by code in the same assembly, as well as by code in
derived classes.
The fields of a class, also called the class's data members, are much like
built-in variables (although they also may be constants). For example, I can declare
VB.Net By Prof.A.D.Chavan 2
Unit-III
a field named value to the DataClass class we just saw by declaring a variable
with that name:
Public Class DataClass
Public value As Integer
End Class
Now I can refer to that field in an object of this class using the familiar object.field
syntax of Visual Basic:
Dim data As New DataClass()
data.value = 5
You also can make fields hold constant values with Const:
Public Class Class1
Public Const Field1 As Integer = 0
⋮
End Class
Using fields like this can give you direct access to the data stored inside an
object, and that's unusual in OOP because you usually want to check the data being
stored in your objects to make sure it's legal first. (For example, you might want to
make sure the number of computers stored in your warehouse is not assigned
negative numbers, and so on.) An easy way of guarding access to the data in your
objects is to use properties. We're all familiar with properties of objects,
TextBox1.Size = New Size(150, 20)
TextBox1.Location = New Point(80, 20)
TextBox1.Text = "Hello from Visual Basic"
Properties are retrieved and set like fields, but are handled with the Property
Get and Property Set procedures, which provide more control on how values are
set or returned. We've first saw how to create properties in Chapter 3. We'll see
more on properties in this chapter, such as creating write-only or read-only
properties.
Methods represent the object's built-in procedures. For example, a class
named Animal may have methods named Sleeping and Eating. You define
methods by adding procedures, either Sub routines or functions, to your class; for
example, here's how I might implement the Sleeping and Eating methods:
Public Class Animal
Public Sub Eating()
MsgBox("Eating...")
End Sub
Public Sub Sleeping()
MsgBox("Sleeping...")
End Sub
End Class
VB.Net By Prof.A.D.Chavan 3
Unit-III
Now I can create a new object of the Animal class and call the Eating method in
the familiar way:
Dim pet As New Animal()
pet.Eating()
And, as we all know, events allow objects to perform actions whenever a
specific occurrence takes place. For example, when you click a button, a Click
event occurs, and you can handle that event in an event handler, as we already have
done so many times. As an example, I'll create a custom event, ThreeClick, in this
chapter, which will happen when you click a button three times. We'll be able to
set up an event handler for that event that looks like this:
Private Sub tracker_ThreeClick(ByVal Message As String) _
Handles tracker.ThreeClick
TextBox1.Text = Message
End Sub
Constructor
A class constructor is a special member Sub of a class that is executed
whenever we create new objects of that class. A constructor has the name new and
it does not have any return type.
Following program explain the concept of constructor:
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
VB.Net By Prof.A.D.Chavan 4
Unit-III
Length of line : 6
A default constructor does not have any parameter but if you need a
constructor can have parameters. Such constructors are called parameterized
constructors. This technique helps you to assign initial value to an object at the
time of its Creation as shown in the following example:
Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
PROGRAM FOR CONSTRUCTOR OVERLOADING
Module Module1
Class cons_over
Dim x, y As Integer
Sub New()
Console.WriteLine("PARAMETERLESS CONSTRUCTOR")
End Sub
Sub New(ByVal x As Integer)
Console.WriteLine(" X = {0} ", x)
End Sub
VB.Net By Prof.A.D.Chavan 5
Unit-III
VB.Net By Prof.A.D.Chavan 7
Unit-III
Destructors
The destructor is the last method run by a class. Destructors in Visual Basic
.NET are implemented as a protected method named Finalize. The garbage
collector will call your Finalize method if you implement one, but you won't know
when that will be you can't invoke this method directly. Finalize method can not
overloaded by convention but must be overridden if you are going to introduce
your own code in this routine by using Overrides keyword in your declaration.
Finalize method invoke automatically when the object is no longer required. The
main works of the destructor is release resources and inform other objects that the
current objects are going to be destroyed.
The following code show you the use of Destructor in Visual Basic .NET:
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
Protected Overrides Sub Finalize() ' destructor
Console.WriteLine("Object is being deleted")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
VB.Net By Prof.A.D.Chavan 8
Unit-III
Inheritance in VB.NET
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an
opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and
the new class is referred to as the derived class.
Base & Derived Classes:
A class can be derived from more than one class or interface, which means that
it can inherit data and functions from multiple base class or interface.
The syntax used in VB.Net for creating derived classes is as follows:
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle:
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
VB.Net By Prof.A.D.Chavan 9
Unit-III
VB.Net By Prof.A.D.Chavan 11
Unit-III
Access modifiers
Access modifiers decide accessibility of your class or class member. There
are five accessibility levels in VB.NET. They are:
Public
Private
Protected
Friend (internal in C#)
Protected friend (protected internal in C#)
Public Access
Many programmers have habit of making everything public in their
applications. This is fine for test applications but when you are developing real life
applications you should expose only the data or functionality that is necessary by
the user of your class. Classes and class members marked with Public access
modifier are available in the same class, all the classes from the same project and
to all other projects as well. This access specifier is least restrictive.
Following is an example of public access specifier.
Public Class Book
Public Title As String
End Class
Public Class BookUser
Public Sub SomeMethod()
Dim x as new Book()
x.Title="VB.NET Programming"
End Sub
End Class
Restricting access to classes and class members is not only a good
programming practice but is also necessary to avoid any accidental misuse of your
classes.
Private Access
Private access modifier is applicable only to the members of a type. It restricts
access to the members within the type itself.
Consider following class:
Public Class Book
Private strTitle As String
Public Property Title()
Get
Return strTitle
End Get
Set(ByVal Value)
strTitle = Value
VB.Net By Prof.A.D.Chavan 12
Unit-III
End Set
End Property
End Class
Here, the member variable strTitle is declared as private inside a class Book.
Hence, it cannot be accessed from outside the class Book. Remember that private
access modifier is applicable only to type members not to the type itself. This
means you cannot declare a class as private but if your class is a nested then it can
be declared as private.
For example following declaration is invalid:
Namespace n1
Private Class Book
End Class
End Namespace
However, following declaration of nested class is valid:
Namespace n1
Public Class Book
Private Class NestedBook
End Class
End Class
End Namespace
Protected Access
Private access modifier allows us to hide members from others but what if
someone is inheriting from your class? In many cases you want that members of
base class should be available in derived class. This cannot be achieved with
private modifier. Protected access specifier provides such access. The members
marked with protected access modifier can be accessed in the same class and all
the classes inherited from it but they are not available to other classes.
Following is an example of using protected access specifier:
Public Class Class1
Protected age As Integer
'... other code
End Class
Public Class Class2
Inherits Class1
Public Sub SomeMethod()
age = 99 'OK
End Sub
End Class
Public Class Class3
Public Sub SomeMethod()
VB.Net By Prof.A.D.Chavan 13
Unit-III
Polymorphism:-
Polymorphism is one of the crucial features of VB.NET, It means "The ability
to take on different form", It is also called as Overloading which means the use of
same thing for different purposes. Using Polymorphism we can create as many
functions we want with one function name but with different argument list. The
function performs different operations based on the argument list in the function
call. The exact function to be invoked will be determined by checking the type and
Number of arguments in the function.
Definition: - "Manipulated the object of various classes and invoke method on one
object without knowing the object type".
Example:-polymorphism real word examples are Student, Manager, Animal and
etc.
Polymorphism can be divide in to two parts, that are given bellow
Compile time polymorphism
Run time polymorphism
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer)
As Integer
'function with three arguments
Return i + j + k
End Function
End Class
Output:10
20
60
Run time Polymorphism:-
Run time polymorphism achieved by "Method Overriding or Operator
Overloading",means that same name function with same parameters in deferent
deferent classes called Run time Polymorphism .
Public Class poly
Public Sub show()
WriteLine("hellow")
End Sub
End Class
Public Class poly2 Inherits poly
Public Sub show()
WriteLine("world")
End Sub
End Class
Class output
Public Shared Sub Main()
Dim a As poly2 = New poly2()
a.show()
End Sub
End Class
Output: World
VB.Net By Prof.A.D.Chavan 18