OOP / VB .
NET
VB.NET -- CLASSES & OBJECTS
• A class is a blue print that describes the general
aspects from which objects are created
• Classes are types and Objects are instances of the
Class. Classes and Objects are very much related to
each other. Without objects you can't use a class
• We humans are very good in recognizing and working with
objects, such as a pen, a dog, or a human being
• A class is a user-defined data type
Defining a Class in VB .NET
• You can declare it as part of a module, but usually in a
separate file (also .vb)
• Ingredients
• Data members (fields)
• Constructors
• Properties
• Methods
• Access Modifiers
• Public: accessible by all
• Private: accessible by the class itself only
• Protected: accessible by the class itself or its sub-classes
• Friend: accessible by all in the current assembly
3
The Syntax for a Class
• Public Class Test
----- Variables
-----Methods
-----Properties
-----Events
End Class
Class Definition
• A class definition starts with the keyword Class followed by
the class name; and the class body, ended by the End Class
statement. Following is the general form of a class
definition:
[ <attributelist> ] [ accessm odifier ] [ Shadows ] [ MustInherit | NotInheritable ] [
Partial ] _
Class nam e [ ( Of typelist ) ]
[ Inherits classnam e ]
[ Im plem ents interfacenam es ]
[ statements ]
End Class
Class Definition
• Where,
~ attributelist is a list of attributes that apply to the class. Optional.
~ accessmodifier defines the access levels of the class, it has values as
- Public, Protected,
~ Friend, Protected Friend and Private. Optional.
~ Shadows indicate that the variable re-declares and hides an
identically named element, or
~ set of overloaded elements, in a base class. Optional.
~ MustInherit specifies that the class can be used only as a base class
and that you cannot
~ create an object directly from it, i.e., an abstract class. Optional.
~ NotInheritable specifies that the class cannot be used as a base
class.
~ Partial indicates a partial definition of the class.
~ Inherits specifies the base class it is inheriting from.
~ Implements specifies the interfaces the class is inheriting from.
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
Box1.height = 5.0 ' box 1 specification
Box1.length = 6.0
Box1.breadth = 7.0
Box2.height = 10.0 ' box 2 specification
Box2.length = 12.0
Box2.breadth = 13.0
volume = Box1.height * Box1.length * Box1.breadth 'volume of box 1
Console.WriteLine("Volume of Box1 : {0}", volume)
volume = Box2.height * Box2.length * Box2.breadth 'volume of box 2
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
OBJECTS
• objects are packages that contain data and functions (methods)
that can be performed on the data.
• Objects are instances of a class. The methods and variables that
constitute a class are called members of the class.
• We some times classify objects based on their attributes, for
example, green apples or red apples, fat or slim people, etc.
• If you think about it each object has many attributes. If I ask you
list the attributes of an orange, you probably could list many
things such as color, shape, weight, smell, etc.
• Data could be considered to be attributes and functions are
considered to be behaviors of the object.
• We can say that the attributes and behaviors are encapsulated
into an object
• The objects interact between each other through their interfaces.
• As an example a date object may have a set of data
consisting of month, day and year, and methods consisting of
assign date, display date, yesterday and tomorrow.
CLASSES AND OBJECTS in VB
• Classes are types and Objects are instances of the
Class.
• Without objects you can't use a class. (Your book
says you can’t drive the drawing of a car)
• In Visual Basic we create a class with the Class
statement and end it with End Class.
• In programming you use a method call to send a
message to the object.
CREATING AN OBJECT
• To create a object for a class (TEST) we use the new
keyword and that looks like this:
Dim obj as new Test().
Dim obj as new Box ()
Sample program
Imports System.Console
Module Module1
Sub Main()
Dim obj As New Test
obj.disp()
Read()
End Sub
End Module
Public Class Test
Sub disp()
'a method named disp in the class
Write("Welcome to OOP")
End Sub
End Class
Members of a class
• Fields, Properties, Methods and Events
• They can be declared as Public, Private, Protected,
Friend or Protected Friend.
• Fields and Properties represent information that
an object contains.
• Fields of a class are like variables and they can be
read or set directly.
• For example, if you have an object named House,
you can store the numbers of rooms in it in a field
named Rooms.
It looks like this:
Public Class House
Public Rooms as Integer
End Class
Properties (Attributes)
⁻Properties are retrieved and set like fields.
⁻If they are public they can be changed by clients.
⁻Private properties are implemented using Property Get
and Property Set procedures which provide more control
on how values are set or returned
Examples:
Amount of Gas in your car
Balance in your bank account
Textbook Example
GradeBook
Public Class GradeBook
Private courseNameValue As String = "Not set yet"
Public Property CourseName() As String
Get
Return courseNameValue
End Get
Set(ByVal value As String)
courseNameValue = value
End Set
End Property
Public Sub displayMessage()
Console.WriteLine("Welcome to the grade book for " &
vbNewLine & courseName & "!")
End Sub
End Class
Textbook Example Module
Module GradeBookTest
Sub Main()
Dim theName As String
Dim gradebook As New GradeBook
Console.WriteLine("Initial course name is: " &
gradebook.CourseName & vbNewLine)
Console.WriteLine("Please enter course name: ")
theName = Console.ReadLine()
gradebook.CourseName = theName
Console.WriteLine()
gradebook.displayMessage()
Console.ReadKey()
End Sub
End Module
Methods (Behavior)
Methods represent the object’s built-in
procedures.
For example, a Class named Country may have
methods named Area and Population
You define methods by adding procedures, Sub
routines or functions to your class.
For example, implementation of the Area and
Population methods discussed above might look
like next slide
Methods defined
Public Class Country
Public Sub Area()
Write("--------")
End Sub
Public Sub population()
Write("---------")
End Sub
End Class
Events
We have been programming for events already.
Events allow objects to perform actions whenever a
specific occurrence takes place. For example when
we click a button a click event occurs and we can
handle that event in an event handler.
Constructors
• A constructor is a special member function whose task
is to initialize the objects of it's class.
• A constructor is invoked whenever an object of it's
associated class is created
• If a class contains a constructor, then an object created
by that class will be initialized automatically.
• We pass data to the constructor by enclosing it in the
parentheses following the class name when creating an
object.
• In Visual Basic we create constructors by adding a Sub
procedure name New to a class.
Imports System.Console
Module Module2
Sub Main()
Dim startObject As New Constructor(10) WriteLine(startObject.display())
'storing a value in the constructor by passing a value(10) and calling it with the
'display method
Read()
End Sub
End Module
Public Class Constructor
Public x As Integer
Public Sub New(ByVal value As Integer)
'constructor
x = value
'storing the value of x in constructor
End Sub
Public Function display() As Integer
Return x
'returning the stored value
End Function
End Class
Destructors
• A destructor is a special member Sub of a class that is executed
whenever an object of its class goes out of scope.
• Destructors run when an object is destroyed.
• Within a destructor we can place code to clean up the object after it is
used.
• We use Finalize method in Visual Basic for this and the Finalize method
is called automatically when the .NET runtime determines that the
object is no longer required.
• When working with destructors we need to use the overrides keyword
with Finalize method as we will override the Finalize method built into
the Object class.
• We normally use Finalize method to deallocate resources and inform
other objects that the current object is going to be destroyed.
• The following code demonstrates the use of Finalize method.
Imports System.Console
Module Module3
Sub Main()
Dim obj As New Destructor
End Sub
End Module
Public Class Destructor
Protected Overrides Sub Finalize()
Write("destroyed!")
Read()
End Sub
End Class
Inheritance
• A key feature of OOP is reusability.
• It's always time saving
• it can be used by other programs to suit the program's
requirement.
• This is done by creating a new class from an existing class.
• The process of deriving a new class from an existing class is called
Inheritance.
• The old class is called the base class
• the new class is called derived class.
• The derived class inherits some or everything of the base class.
• In Visual Basic we use the Inherits keyword to inherit one class
from other.
Inheritance coding
Public Class One
---
---
End Class
Public Class Two
Inherits One
---
---
End Class
Inheritance coding (2)
mports System.Console
Module Module4
Sub Main()
Dim ss As New Two
WriteLine(ss.sum())
Read()
End Sub
End Module
(see next slide for inheritance)
Public Class One
Public i As Integer = 10
Public j As Integer = 20
Public Function add() As Integer
Return i + j
End Function
End Class
Public Class Two
Inherits One
Public k As Integer = 100
Public Function sum() As Integer
'using the variables, function from base class and adding more
functionality
Return i + j + k
End Function
End Class
Polymorphism
It means "one name, multiple forms".
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.
Analogy:If you are asked to open you will know what to
do depending on what the object you are working with:
a door, a jar, an envelope, etc.
Polymorphism Code
Imports System.Console
Module Module5
Sub Main()
Dim two As New One1
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
Read()
End Sub
End Module
Public Class One1
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
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
Interfaces
• allow us to create definitions for component interaction.
• They also provide another way of implementing polymorphism.
• Through interfaces, we specify methods that a component must
implement without actually specifying how the method is
implemented.
• We just specify the methods in an interface and leave it to the
class to implement those methods.
• Visual Basic .NET does not support multiple inheritance directly
but using interfaces we can achieve multiple inheritance.
• We use the Interface keyword to create an interface and
implements keyword to implement the interface.
• Once you create an interface you need to implement all the
methods specified in that interface.
•
Imports System.Console
Module interfaces
Sub Main()
Dim OneObj As New One
Dim TwoObj As New Two
'creating objects of class One and Two
OneObj.disp()
OneObj.multiply()
TwoObj.disp()
TwoObj.multiply()
'accessing the methods from classes as
specified in the interface
End Sub
End Module
Public Interface Test
'creating an Interface named Test
Sub disp()
Function Multiply() As Double
'specifying two methods in an
interface
End Interface
Public Class One
Implements Test
'implementing interface in class One
Public i As Double = 12
Public j As Double = 12.17
Sub disp() Implements Test.disp
'implementing the method specified in interface
WriteLine("sum of i+j is" & i + j)
Read()
End Sub
Public Function multiply() As Double Implements Test.Multiply
'implementing the method specified in interface
WriteLine(i * j)
Read()
End Function
End Class
Public Class Two
Implements Test
'implementing the interface in class Two
Public a As Double = 20
Public b As Double = 32.17
Sub disp() Implements Test.disp
WriteLine("Welcome to Interfaces")
Read()
End Sub
Public Function multiply() As Double Implements
Test.Multiply
WriteLine(a * b)
Read()
End Function
End Class
Abstract Classes
• An abstract class is the one that is not used to create objects.
• An abstract class is designed to act as a base class (to be inherited
by other classes).
• Abstract class is a design concept in program development and
provides a base upon which other classes are built.
• Abstract classes are similar to interfaces.
• After declaring an abstract class, it cannot be instantiated on it's
own, it must be inherited.
• Like interfaces, abstract classes can specify members that must
be implemented in inheriting classes.
• Unlike interfaces, a class can inherit only one abstract class.
Abstract classes can only specify members that should be
implemented by all inheriting classes
Creating Abstract
Classes
• In Visual Basic .NET we create an abstract class by
using the MustInherit keyword.
• An abstract class like all other classes can
implement any number of members.
• Members of an abstract class can either be
Overridable (all the inheriting classes can create
their own implementation of the members) or they
can have a fixed implementation that will be
common to all inheriting members.
Creating abstract
classes(2)
• Abstract classes can also specify abstract
members.
• Like abstract classes, abstract members also
provide no details regarding their implementation.
• Only the member type, access level, required
parameters and return type are specified.
• To declare an abstract member we use the
MustOverride keyword.
• Abstract members should be declared in abstract
classes.
Imports System.Console
Module abstractClasses
Public MustInherit Class AbstractClass
'declaring an abstract class with MustInherit keyword
Public MustOverride Function Add() As Integer
Public MustOverride Function Mul() As Integer
'declaring two abstract members with MustOverride keyword
End Class
Public Class AbstractOne
Inherits AbstractClass
'implementing the abstract class by inheriting
Dim i As Integer = 20
Dim j As Integer = 30
'declaring two integers
Public Overrides Function Add() As Integer
Return i + j
End Function
'implementing the add method
Public Overrides Function Mul() As Integer
Return i * j
End Function
'implementing the mul method
End Class
Sub Main()
Dim abs As New AbstractOne
'creating an instance of AbstractOne
WriteLine("Sum is" & " " & abs.Add())
WriteLine("Multiplication is" & " " &
abs.Mul())
'displaying output
Read()
End Sub
End Module
Structures
• Structures can be defined as a tool for handling a
group of logically related data items.
• They are user-defined and provide a method for
packing together data of different types. Structures
are very similar to Classes.
• Like Classes, they too can contain members such as
fields and methods.
Structures
• The main difference between classes and
structures is, classes are reference types and
structures are value types.
• In practical terms, structures are used for smaller
lightweight objects that do not persist for long and
classes are used for larger objects that are
expected to exist in memory for long periods.
• We declare a structure in Visual Basic .NET with the
Structure keyword.