Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 39

Module 5: Object-

Oriented Programming
in Visual Basic .NET
Overview

 Defining Classes
 Creating and Destroying Objects
 Inheritance
 Interfaces
 Working with Classes
 Defining Classes

 Procedure for Defining a Class


 Using Access Modifiers
 Declaring Methods
 Declaring Properties
 Using Attributes
 Overloading Methods
 Using Constructors
 Using Destructors
Procedure for Defining a Class

Add a class to the project

Provide an appropriate name for the class

Create constructors as needed

Create a destructor, if appropriate

Declare properties

Declare methods and events


Using Access Modifiers

 Specify accessibility of variables and procedures


Keyword Definition
Public Accessible everywhere.
Private Accessible only within the type itself.

Friend Accessible within the type itself and all


namespaces and code within the same assembly.
Protected Only for use on class members. Accessible within
the class itself and any derived classes.
Protected The union of Protected and Friend.
Friend
Declaring Methods

 Same syntax as in Visual Basic 6.0

Public
Public Sub
Sub TestIt(ByVal
TestIt(ByVal xx As
As Integer)
Integer)
...
...
End
End Sub
Sub

Public
Public Function
Function GetIt(
GetIt( )) As
As Integer
Integer
...
...
End
End Function
Function
Declaring Properties

 Syntax differs from that of Visual Basic 6.0


Public
Public Property
Property MyData(
MyData( )) As
As Integer
Integer
Get
Get
Return
Return intMyData
intMyData 'Return
'Return local
local variable
variable value
value
End
End Get
Get
Set
Set (ByVal Value
(ByVal Value As
As Integer)
Integer)
intMyData = Value
intMyData = Value 'Store
'Store Value
Value in
in local
local variable
variable
End Set
End Set
End Property
End Property

 ReadOnly, WriteOnly, and Default keywords


Public
Public ReadOnly
ReadOnly Property
Property MyData(
MyData( )) As
As Integer
Integer
Get
Get
Return
Return intMyData
intMyData
End Get
End Get
End Property
End Property
Using Attributes

 Extra metadata supplied by using “< >” brackets


 Supported for:
 Assemblies, classes, methods, properties, and more
 Common uses:
 Assembly versioning, Web Services, components,
security, and custom
<Obsolete("Please
<Obsolete("Please use
use method
method M2")>
M2")> Public
Public Sub
Sub M1(
M1( ))
'Results
'Results in
in warning
warning in
in IDE
IDE when
when used
used by
by client
client code
code
End
End Sub
Sub
Overloading Methods

 Methods with the same name can accept different


parameters
Public
Public Function
Function Display(s
Display(s As
As String)
String) As
As String
String
MsgBox("String:
MsgBox("String: "" && s)
s)
Return
Return "String"
"String"
End Sub
End Sub
Public
Public Function
Function Display(i
Display(i As
As Integer)
Integer) As
As Integer
Integer
MsgBox("Integer: " & i)
MsgBox("Integer: " & i)
Return
Return 11
End
End Function
Function

 Specified parameters determine which method to call


 The Overloads keyword is optional unless overloading
inherited methods
Using Constructors

 Sub New replaces Class_Initialize


 Executes code when object is instantiated
Public
Public Sub
Sub New(
New( ))
'Perform
'Perform simple
simple initialization
initialization
intValue =
intValue = 11
End Sub
End Sub

 Can overload, but does not use Overloads keyword


Public
Public Sub
Sub New(ByVal
New(ByVal ii As
As Integer)
Integer) 'Overloaded
'Overloaded without
without Overloads
Overloads
'Perform
'Perform more
more complex
complex initialization
initialization
intValue =
intValue = ii
End Sub
End Sub
Using Destructors

 Sub Finalize replaces Class_Terminate event


 Use to clean up resources
 Code executed when destroyed by garbage collection
 Important: destruction may not happen immediately

Protected
Protected Overrides
Overrides Sub
Sub Finalize(
Finalize( ))
'Can
'Can close
close connections
connections or
or other
other resources
resources
conn.Close
conn.Close
End
End Sub
Sub
 Creating and Destroying Objects

 Instantiating and Initializing Objects


 Garbage Collection
 Using the Dispose Method
Instantiating and Initializing Objects

 Instantiate and initialize objects in one line of code

'Declare
'Declare butbut do
do not
not instantiate
instantiate yet
yet
Dim
Dim c1
c1 As
As TestClass
TestClass
'Other
'Other code
code
c1
c1 == New
New TestClass(
TestClass( )) 'Instantiate
'Instantiate now
now

'Declare,
'Declare, instantiate
instantiate && initialize
initialize using
using default
default constructor
constructor
Dim c2 As TestClass = New TestClass(
Dim c2 As TestClass = New TestClass( ) )

'Declare,
'Declare, instantiate
instantiate && initialize
initialize using
using default
default constructor
constructor
Dim c3 As New TestClass
TestClass(
Dim c3 As New TestClass(
TestClass ) )

'Declare,
'Declare, instantiate
instantiate && initialize
initialize using
using alternative
alternative constructor
constructor
Dim
Dim c4
c4 As
As New
New TestClass(10)
TestClass(10)
Dim
Dim c5
c5 As
As TestClass
TestClass == New
New TestClass(10)
TestClass(10)
Garbage Collection

 Background process that cleans up unused variables


 Use x = Nothing to enable garbage collection
 Detects objects or other memory that cannot be reached by
any code (even circular references!)
 Allows destruction of object
 No guarantee of when this will happen
 Potential for resources to be tied up for long periods of
time (database connections, files, and so on)
 You can force collection by using the GC system class
Using the Dispose Method

 Create a Dispose method to manually release resources


'Class
'Class code
code
Public
Public Sub
Sub Dispose(
Dispose( ))
'Check
'Check that
that the
the connection
connection isis still
still open
open
conn.Close
conn.Close 'Close
'Close aa database
database connection
connection
End
End Sub
Sub

 Call the Dispose method from client code


'Client
'Client code
code
Dim
Dim x as
x as TestClass
TestClass == New
New TestClass(
TestClass( ))
...
...
x.Dispose(
x.Dispose( )) 'Call
'Call the
the object's
object's dispose
dispose method
method
Demonstration: Creating Classes
Lab 5.1: Creating the Customer Class
 Inheritance

 What Is Inheritance?
 Overriding and Overloading
 Inheritance Example
 Shadowing
 Using the MyBase Keyword
 Using the MyClass Keyword
What Is Inheritance?

 Derived class inherits from a base class


 Properties, methods, data members, events, and event
handlers can be inherited (dependent on scope)
 Keywords
 Inherits – inherits from a base class
 NotInheritable – cannot be inherited from
 MustInherit – instances of the class cannot be created;
must be inherited from as a base class
 Protected – member scope that allows use only by
deriving classes
Overriding and Overloading

 Derived class can override an inherited property or method


 Overridable – can be overridden
 MustOverride – must be overridden in derived class
 Overrides – replaces method from inherited class
 NotOverridable – cannot be overridden (default)
 Use Overload keyword to overload inherited property or
method
Inheritance Example
Public
Public Class
Class BaseClass
BaseClass
Public
Public Overridable
Overridable Sub
Sub OverrideMethod(
OverrideMethod( ))
MsgBox("Base
MsgBox("Base OverrideMethod")
OverrideMethod")
End
End Sub
Sub
Public
Public Sub
Sub Other(
Other( ))
MsgBox("Base
MsgBox("Base Other
Other method
method –– not
not overridable")
overridable")
End Sub
End Sub
End Class
End Class
Public
Public Class
Class DerivedClass
DerivedClass
Inherits BaseClass
Inherits BaseClass
Public
Public Overrides
Overrides Sub
Sub OverrideMethod(
OverrideMethod( ))
MsgBox("Derived
MsgBox("Derived OverrideMethod")
OverrideMethod")
End Sub
End Sub
End Class
End Class

Dim
Dim xx As
As DerivedClass
DerivedClass == New
New DerivedClass(
DerivedClass( ))
x.Other(
x.Other( )) 'Displays
'Displays "Base
"Base Other
Other method
method –– not
not overridable"
overridable"
x.OverrideMethod( ) 'Displays "Derived OverrideMethod"
x.OverrideMethod( ) 'Displays "Derived OverrideMethod"
Shadowing

 Hides base class members, even if overloaded


Class
Class aBase
aBase
Public
Public Sub
Sub M1(
M1( )) 'Non-overridable
'Non-overridable by
by default
default
...
...
End
End Sub
Sub
End
End Class
Class
Class
Class aShadowed
aShadowed
Inherits
Inherits aBase
aBase
Public
Public Shadows Sub
Shadows Sub M1(ByVal
M1(ByVal ii As
As Integer)
Integer)
'Clients
'Clients can
can only
only see
see this
this method
method
...
...
End
End Sub
Sub
End Class
End Class
Dim
Dim xx As
As New
New aShadowed(
aShadowed( ))
x.M1(
x.M1( )) 'Generates
'Generates an
an error
error
x.M1(20)
x.M1(20) 'No error
'No error
Using the MyBase Keyword

 Refers to the immediate base class


 Can only access public, protected, or friend members of
base class
 Is not a real object (cannot be stored in a variable)
Public
Public Class
Class DerivedClass
DerivedClass
Inherits
Inherits BaseClass
BaseClass
Public
Public Overrides
Overrides Sub
Sub OverrideMethod(
OverrideMethod( ))
MsgBox("Derived
MsgBox("Derived OverrideMethod")
OverrideMethod")
MyBase.OverrideMethod(
MyBase.OverrideMethod( ))
End
End Sub
Sub
End
End Class
Class
Using the MyClass Keyword

 Ensures that base class gets called, not derived class


Public
Public Class
Class BaseClass
BaseClass
Public
Public Overridable
Overridable Sub
Sub OverrideMethod(
OverrideMethod( ))
MsgBox("Base
MsgBox("Base OverrideMethod")
OverrideMethod")
End
End Sub
Sub
Public
Public Sub
Sub Other(
Other( ))
MyClass.OverrideMethod(
MyClass.OverrideMethod( ))'Will
'Will call
call above
above method
method
OverrideMethod(
OverrideMethod( )) 'Will
'Will call
call derived
derived method
method
End
End Sub
Sub
End
End Class
Class

Dim
Dim xx As
As DerivedClass
DerivedClass == New
New DerivedClass(
DerivedClass( ))
x.Other(
x.Other( ))
Demonstration: Inheritance
 Interfaces

 Defining Interfaces
 Achieving Polymorphism
Defining Interfaces

 Interfaces define public procedure, property, and event


signatures
 Use the Interface keyword to define an interface module
 Overload members as for classes
Interface
Interface IMyInterface
IMyInterface
Function
Function Method1(ByRef
Method1(ByRef ss AsAs String)
String) As
As Boolean
Boolean
Sub
Sub Method2(
Method2( ))
Sub
Sub Method2(ByVal
Method2(ByVal ii As
As Integer)
Integer)
End
End Interface
Interface
 Use the Inherits keyword in an interface to inherit from other
interfaces
Achieving Polymorphism

 Polymorphism
 Many classes provide the same property or method
 A caller does not need to know the type of class the
object is based on
 Two approaches
 Interfaces
Class implements members of interface
Same approach as in Visual Basic 6.0
 Inheritance
Derived class overrides members of base class
Demonstration: Interfaces and Polymorphism
 Working with Classes

 Using Shared Data Members


 Using Shared Procedure Members
 Event Handling
 What Are Delegates?
 Using Delegates
 Comparing Classes to Structures
Using Shared Data Members

 Allow multiple class instances to refer to a single class-level


variable instance
Class
Class SavingsAccount
SavingsAccount
Public
Public Shared
Shared InterestRate
InterestRate AsAs Double
Double
Public
Public Name
Name As
As String,
String, Balance
Balance As
As Double
Double
Sub
Sub New(ByVal
New(ByVal strName
strName As
As String,
String, ByVal
ByVal dblAmount
dblAmount As
As Double)
Double)
Name = strName
Name = strName
Balance
Balance == dblAmount
dblAmount
End Sub
End Sub
Public
Public Function
Function CalculateInterest(
CalculateInterest( )) AsAs Double
Double
Return Balance * InterestRate
Return Balance * InterestRate
End Function
End Function
End Class
End Class

SavingsAccount.InterestRate
SavingsAccount.InterestRate == 0.003
0.003
Dim
Dim acct1
acct1 As
As New
New SavingsAccount("Joe
SavingsAccount("Joe Howard",
Howard", 10000)
10000)
MsgBox(acct1.CalculateInterest,
MsgBox(acct1.CalculateInterest, , "Interest for "" && acct1.Name)
, "Interest for acct1.Name)
Using Shared Procedure Members

 Share procedures without declaring a class instance


 Similar functionality to Visual Basic 6.0 “global” classes
 Can only access shared data

'TestClass
'TestClass code
code
Public
Public Shared
Shared Function
Function GetComputerName(
GetComputerName( )) As
As String
String
...
...
End
End Function
Function

'Client
'Client code
code
MsgBox(TestClass.GetComputerName(
MsgBox(TestClass.GetComputerName( ))
))
Event Handling

 Defining and raising events: same as Visual Basic 6.0


 WithEvents keyword: handles events as in Visual Basic 6.0
 In Visual Basic .NET, works with Handles keyword to specify
method used to handle event
 AddHandler keyword: allows dynamic connection to events
Dim
Dim xx As
As New
New TestClass(
TestClass( ),
), yy As
As New
New TestClass(
TestClass( ))
AddHandler
AddHandler x.anEvent,
x.anEvent, AddressOf
AddressOf HandleEvent
HandleEvent
AddHandler y.anEvent, AddressOf HandleEvent
AddHandler y.anEvent, AddressOf HandleEvent
...
...

Sub
Sub HandleEvent(ByVal
HandleEvent(ByVal ii As
As Integer)
Integer)
...
...
End Sub
End Sub

 RemoveHandler keyword: disconnects from event source


Demonstration: Handling Events
What Are Delegates?

 Objects that call the methods of other objects


 Similar to function pointers in Visual C++
 Reference type based on the System.Delegate class
 Type-safe, secure, managed objects
 Example:
 Useful as an intermediary between a calling procedure
and the procedure being called
Using Delegates

 Delegate keyword declares a delegate and defines


parameter and return types

Delegate
Delegate Function
Function CompareFunc(
CompareFunc( __
ByVal
ByVal xx As
As Integer,
Integer, ByVal
ByVal yy As
As Integer)
Integer) As
As Boolean
Boolean

 Methods must have the same function parameter and return


types
 Use Invoke method of delegate to call methods
Comparing Classes to Structures

Classes Structures
Can define data members, Can define data members,
properties, and methods properties, and methods
Support constructors and No default constructor or
member initialization member initialization
Support Finalize method Do not support Finalize method
Extensible by inheritance Do not support inheritance
Reference type Value type
Lab 5.2: Inheriting the Package Class
Review

 Defining Classes
 Creating and Destroying Objects
 Inheritance
 Interfaces
 Working with Classes

You might also like