0% found this document useful (0 votes)
209 views

Unit Iii

The document discusses object-oriented programming concepts in VB.NET, including classes, objects, constructors, and class members. It provides examples of how to define a class with methods and properties, and how to create object instances that can access these members. A key point is that a constructor is called automatically when an object is instantiated in order to initialize the object's fields. Constructors can be overloaded to initialize fields differently based on parameter values passed to the constructor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views

Unit Iii

The document discusses object-oriented programming concepts in VB.NET, including classes, objects, constructors, and class members. It provides examples of how to define a class with methods and properties, and how to create object instances that can access these members. A key point is that a constructor is called automatically when an object is instantiated in order to initialize the object's fields. Constructors can be overloaded to initialize fields differently based on parameter values passed to the constructor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-III

 Object Oriented Programming


 Classes in VB.NET
Classes in VB.net is type used to create data or objects that are instances of a
class. Objects and classes are so closely associated with each other, so that classes
can be used only if it contains objects. The Scope of usage of classes and the
objects are based on the access types used when they are declared as Public,
Private, Friend and Protected.
Example:
Module Module1
Public Class Add
Dim i, j As Integer
Public Sub Display()
System.Console.WriteLine("Enter First Integer:")
i = Console.ReadLine()
System.Console.WriteLine("Enter Second Integer:")
j = Console.ReadLine()
Console.WriteLine("Result of Addition is:" & (i + j))
End Sub
End Class
Sub Main()
Dim add1 As New Add
add1.Display()
Console.Read()
End Sub
End Module
Result:
Enter First Integer:
2
Enter Second Integer:
3
Result of Addition is:
5
In the above example, class Add is declared as 'Public', so that the method display
is derived and used by creating an instance add1 inside sub main().
 Objects in VB.NET
Objects in VB.net are instances of a class. Advantage of objects is that it can be
used flexibly by referring the class name without the need to write code.
Every object that has its own Properties, Methods and Events. Properties of the
object define the characteristics, the Methods define the procedure that can operate
on a Object. The events are possible actions that can occur to an object
VB.Net By Prof.A.D.Chavan 1
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

Sub New(ByVal x As Integer, ByVal y As Integer)


Console.WriteLine(" {0} + {1} = {2}", x, y, x + y)
End Sub
End Class
Sub Main()
Dim x, y As Integer
Console.WriteLine("ENTER A NUMBER")
x = CInt(Console.ReadLine())
Console.WriteLine("ENTER A NUMBER")
y = CInt(Console.ReadLine())
Dim C1, C2, C3 As cons_over
C1 = New cons_over()
C2 = New cons_over(x)
C3 = New cons_over(x, y)
Console.Read()
End Sub
End Module
ENTER A NUMBER
17
ENTER A NUMBER
23
PARAMETERLESS CONSTRUCTOR
X = 17
17 + 23 = 40
A Constructor is a special kinds of member function that used to initialize
the object .A constructor is like a method in that it contain executable code and
may be defined with parameter. this is first method that is run when an instance of
type is created. Constructor is two types in VB.NET
 Instance constructor
 Shared constructor
 Instance constructor:-"An Instance constructor runs whenever the CLR
creates an object from a class"
coding for instance constructor:-
Module Module1
Sub Main()
Dim con As New Constructor("Hello world")
Console.WriteLine(con.display())
'display method
End Sub
End Module
VB.Net By Prof.A.D.Chavan 6
Unit-III

Public Class Constructor


Public x As String
Public Sub New(ByVal value As String)
'constructor
x = value
'storing the value of x in constructor
End Sub
Public Function display() As String
Return x
'returning the stored value
End Function
End Class
Output:- Hellow world
 Shared Constructor:-"Shared constructor are most often used to initialize
class level data such as shared fields"
coding for shared constructor:-
Module Testcons
Sub Main()
Console.WriteLine("100")
B.G()
Console.WriteLine("200")
End Sub
End Module
Class A
Shared Sub New()
Console.WriteLine("Init A")
End Sub
End Class
Class B Inherits A
Shared Sub New()
Console.WriteLine("Init B")
End Sub
Public Shared Sub G()
Console.WriteLine("Hello world")
End Sub
End Class
Output: 100
200
Hello world

VB.Net By Prof.A.D.Chavan 7
Unit-III

Note: Some important points for shared constructor


 Shared constructors are run before any instance of a class type is created.
 Shared constructors are run before any instance members of a structure type
are accessed, or before any constructor of a structure type is explicitly
called. Calling the implicit parameter less constructor created for structures
will not cause the shared constructor to run.
 Shared constructors are run before any of the type's shared members are
referenced.
 Shared constructors are run before any types that derive from the type are
loaded.
 A shared constructor will not be run more than once during a single
execution of a program.

 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

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
Length of line : 6
Object is being deleted

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

Public Sub setHeight(ByVal h As Integer)


height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Total area: 35
Base Class Initialization
The derived class inherits the base class member variables and member
methods. Therefore the super class object should be created before the subclass is
created. The super class or the base class is implicitly known as MyBase in VB.Net
The following program demonstrates this:
' Base class
Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
VB.Net By Prof.A.D.Chavan 10
Unit-III

Console.WriteLine("Width: {0}", width)


Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

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

Dim x As New Class1()


x.age = 99 'ERROR
End Sub
End Class
 Friend Access
Now going one step further let us assume that you want that all the classes
from your project should be able to access to your class members but classes
external to your project should not be able to do so. In this case neither private nor
protected can help. Only your Friend can help you out. You guessed it! The friend
access modifier is used to declare your class members such that any class from the
same project will be able to access them but external classes cannot. Note that this
access modifier is applicable to class definitions also.
Following are the examples of using Friend members and classes.
Assembly1.dll
Public Class Class1
Friend age As Integer
'... other code
End Class
Public Class Class2
Public Sub SomeMethod()
Dim x As New Class1()
x.age = 99 'OK
End Sub
End Class
Assembly2.dll
Public Class Class3
Public Sub SomeOtherMethod()
Dim x As New Class1()
x.age = 99 'ERROR
End Sub
End Class
When applied to class the class will be available only in the project in which it is
declared.
Assembly1.dll
Friend Class Class3
Public Sub SomeMethod()
End Sub
End Class
Public Class Class4
Public Sub SomeOtherMethod()
VB.Net By Prof.A.D.Chavan 14
Unit-III

Dim x As Class3 'OK


End Sub
End Class
Assembly2.dll
Dim x As TestComp1.n1.Class3 'ERROR
Note: In C# internal keyword serves the same purpose as Friend keyword in
VB.NET.
 Protected Friend Access
Protected Friend access modifier is a combination of protected and friend
access modifiers and allows access to class members in the same project and all the
inherited types.
 Overloading in VB.NET
Overloading in visual basic.net is the method by which a property or a method
takes different forms at different instances. It can also be termed as
"Polymorphism".
Example:
Module Module1
Public Class mul
Public a, b As Integer
Public c, d As Double
Public Function mul(ByVal a As Integer) As Integer
Return a
End Function
Public Function mul(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function
Public Function mul(ByVal d As Double, ByVal c As Double) As Double
Return d * c
End Function
End Class
Sub Main()
Dim res As New mul
System.Console.WriteLine
("Overloaded Values of Class Mul is::")
System.Console.WriteLine(res.mul(10))
System.Console.WriteLine(res.mul(20, 10))
System.Console.WriteLine(res.mul(12.12, 13.23))
Console.Read()
End Sub End Module
Result:
VB.Net By Prof.A.D.Chavan 15
Unit-III

Overloaded values of Class Mul is:


10
200
160.3476
In the above overloading example the same function mul is called to perform
different operations based on the arguments as well as on the datatype.
 Overriding in VB.NET
Overriding in VB.net is method by which a inherited property or a method is
overidden to perform a different functionality in a derived class. The base class
function is declared using a keyword Overridable and the derived class function
where the functionality is changed contains an keyword Overrides.
Example:
Module Module1
Class Over
Public Overridable Function add(ByVal x As Integer,ByVal y As Integer)
Console.WriteLine('Function Inside Base Class')
Return (x + y)
End Function
End Class
Class DerOver Inherits Over Public Overrides Function add(ByVal x As
Integer,ByVal y As Integer)
Console.WriteLine(MyBase.add(120, 100))
Console.WriteLine('Function Inside Derived Class')
Return (x + y)
End Function
End Class
Sub Main()
Dim obj As New DerOver
Console.WriteLine(obj.add(10, 100))
Console.Read()
End Sub
End Module
Result:
Function Inside Base Class
220
Function Inside Derived Class
110
In the above overriding example the base class function add is overridden in
the derived class using the MyBase.add(120,100) statement. So first the overidden
value is displayed, then the value from the derived class is displayed.
VB.Net By Prof.A.D.Chavan 16
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

 Compile time polymorphism:-


Compile time polymorphism achieved by "Method Overloading", means that
same name function with deferent parameters in same class called compile time
polymorphism.
Module Module1
Sub Main()
Dim two As New One()
WriteLine(two.add(10))
'calls the function with one argument
WriteLine(two.add(10, 20))
'calls the function with two arguments
WriteLine(two.add(10, 20, 30))
'calls the function with three arguments
End Sub
End Module
Public Class One
Public i, j, k As Integer
Public Function add(ByVal i As Integer) As Integer
'function with one argument
Return i
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer
'function with two arguments
Return i + j
VB.Net By Prof.A.D.Chavan 17
Unit-III

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy