Module 5 - Object-Oriented Programming in Visual Basic
Module 5 - Object-Oriented Programming in Visual Basic
Oriented Programming
in Visual Basic .NET
Contents
Overview 1
Defining Classes 2
Creating and Destroying Objects 16
Demonstration: Creating Classes 23
Lab 5.1: Creating the Customer Class 24
Inheritance 31
Demonstration: Inheritance 43
Interfaces 44
Demonstration: Interfaces and
Polymorphism 50
Working with Classes 51
Lab 5.2: Inheriting the Package Class 65
Review 74
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript,
Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual
InterDev, Visual Studio, and Windows Media are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 5: Object-Oriented Programming in Visual Basic .NET iii
Instructor Notes
Presentation: This module provides students with the knowledge required to create object-
90 Minutes oriented applications that use many of the new features of Microsoft®
Visual Basic ® .NET, such as inheritance, overloading, shared members, and
Labs: event handling.
105 Minutes
In the first lab, students will create part of the Customer class for the Cargo
system that they designed in Lab 4.1, Creating Diagrams from Use Cases. They
will define the properties, methods, and constructors, based on those shown in
Lab 4.1. Finally, they will write the code in a form to test the Customer class.
In the second lab, students will create a base class called Package and a derived
class called SpecialPackage. The classes contain some pre-written code,
including the properties. Students will add methods to both classes and create
the inheritance relationship. They will then complete a pre-written form to test
their classes.
After completing this module, students will be able to:
n Define classes.
n Instantiate and use objects in client code.
n Create classes that use inheritance.
n Define interfaces and use polymorphism.
n Create shared members.
n Create class events and handle them from a client application.
iv Module 5: Object-Oriented Programming in Visual Basic .NET
Required Materials
To teach this module, you need the following materials:
n Microsoft PowerPoint® file 2373A_05.ppt
n Module 5, “Object-Oriented Programming in Visual Basic .NET”
n Lab 5.1, Creating the Customer Class
n Lab 5.2, Inheriting the Package Class
Preparation Tasks
To prepare for this module, you should:
n Read all of the materials for this module.
n Read the instructor notes and the margin notes for the module.
n Practice the demonstrations.
n Complete the labs.
Module 5: Object-Oriented Programming in Visual Basic .NET v
Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Creating Classes
å To examine the Employee class
1. Open the Classes.sln solution in the install folder\DemoCode\
Mod05\Classes folder.
2. View the code for the Employee class and point out the private variables,
the properties, and the multiple constructors. Specifically point out the
EmployeeId read-only property.
Inheritance
å To examine the Person class
1. Open the Inheritance.sln solution in the install folder\DemoCode\
Mod05\Inheritance folder.
2. View the code for the Person class, and point out the private variables, the
properties, and the methods.
3. View the code for the Employee class, and point out that it is a simplified
version of the class used in the previous demonstration in that it has only
one constructor. Show that it inherits from the Person class and only stores
the EmployeeId value. Also, point out that the FirstName and LastName
properties are not defined in this class.
Module 5: Object-Oriented Programming in Visual Basic .NET vii
Handling Events
å To view the code
1. Open the Events.sln solution in the install folder\DemoCode\Mod05\Events
folder.
2. View the code for the Employee class, and point out the DataChanged
event in the declarations section and its purpose. In the FirstName property,
point out the raising of the event and the purpose of the code that checks the
blnCancelled value.
3. View the code for the frmEvents form, and point out the module-level
variable that uses WithEvents.
4. Click the Class Name combo box, and then click empEmployee. In the
Method Name combo box, click DataChanged. Examine the default event
handler code, and point out the Handles keyword in the function declaration.
Module Strategy
Use the following strategy to present this module:
n Defining Classes
This lesson describes how to create classes in Visual Basic .NET. Students
will learn how to declare methods and properties, and how to overload class
members. When you introduce students to class constructors and destructors,
including multiple constructors, point out that the Finalize method should
only be used when resources need to be manually reclaimed (such as
database connections) because this method adds overhead to the disposing
of objects.
Some of this lesson contains simple tasks such as how to create classes and
methods. Cover these areas quickly so that more time can be spent on new
features, such as the syntax for defining properties and constructors.
n Creating and Destroying Objects
This lesson describes how to declare, instantiate, and initialize objects.
Contrast this approach to the approach used in previous versions of
Visual Basic to show the usefulness of constructors.
Introduce garbage collection as an important change in the way objects are
destroyed. Ensure that students understand this process, because many
developers will be unaware of the potential dangers. Present the Dispose
method as a suggested way to handle issues raised by garbage collection.
Point out that the notes present two common techniques for creating the
Dispose method, and that the IDisposable interface provides a more
consistent approach. If time permits, you may want to show students the
“GC Class”topic in the Visual Studio .NET documentation.
Use the instructor-led demonstration to demonstrate how to create classes
that contain multiple constructors. In this demonstration, you will also show
how to instantiate and use classes from calling code.
Have students complete the first lab after the demonstration.
n Inheritance
This lesson explains how to use the new Visual Basic .NET class
inheritance features. Introduce students to member overriding, the MyBase
keyword, and the MyClass keyword. These important features will be new
to many students, so be prepared to demonstrate different scenarios to
reiterate the concepts.
Use the instructor-led inheritance demonstration to show how to use the
various keywords to create a simple Person class that is used as a base class
for an Employee class.
x Module 5: Object-Oriented Programming in Visual Basic .NET
n Interfaces
This lesson explains how to define interfaces in Visual Basic .NET and
examines the various ways to achieve polymorphism.
Use the instructor-led polymorphism demonstration to show how to use
interfaces to define an IPerson interface that is then implemented by
Student and Employee classes.
This lesson will be a challenge for many students. You will need to gauge
the level of understanding and decide how much time to spend on the
material and the demonstration. Tell students where they can find additional
information about this topic, possibly including books or white papers.
For more information about interfaces and polymorphism, search for
“interfaces and polymorphism” in the Visual Studio .NET documentation
and at http://msdn.microsoft.com
n Working with Classes
This lesson shows how to create shared members, events, and delegates.
The Event Handing topic mentions the AddressOf operator but does not
explain it in depth because it is not new to Visual Basic .NET. Some
students, however, may require a more detailed explanation.
Students may also find the concept of delegates to be difficult. A detailed
example is provided in the student notes, and you may need to go through
this example with the students. This example is also provided in the
DemoCode folder, although no instructions accompany this code.
Use the instructor-led demonstration to show how to define and handle
events in a simple class.
Module 5: Object-Oriented Programming in Visual Basic .NET 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. n Defining Classes
Lead-in
In this module, you will learn
n Creating and Destroying Objects
how to implement object- n Inheritance
oriented programming in
Visual Basic .NET. n Interfaces
n Working with Classes
u Defining Classes
Topic Objective
To provide an overview of
the topics covered in this
lesson. n Procedure for Defining a Class
Lead-in
This lesson explains how to n Using Access Modifiers
define classes. n Declaring Methods
n Declaring Properties
n Using Attributes
n Overloading Methods
n Using Constructors
n Using Destructors
In this lesson, you will learn how to define classes in Visual Basic .NET. After
completing this lesson, you will be able to:
n Specify access modifiers (scope) for classes and their procedures.
n Declare methods and properties within a class.
n Use attributes to provide metadata about your code.
n Pass different parameters to one method by using overloading.
n Create and destroy objects.
Module 5: Object-Oriented Programming in Visual Basic .NET 3
Declare Properties
To define a class in Visual Basic .NET, you can follow this general procedure:
1. Add a class to the project.
Delivery Tip
Point out that you can define 2. Provide an appropriate file name for the class when you add it. This will
as many classes as you name both the file and the class itself. If you do not change the file name
need in a module. You are when you add it, you can change the class name at any time by changing the
not limited to one class per class definition in the code window.
file, as you are in previous
versions of Visual Basic. 3. Create constructors as needed.
4. Create a destructor if appropriate.
5. Declare properties.
6. Declare methods and events.
Note In Visual Basic .NET, you can define more than one class in a single file.
You are not limited to one class per file, as you are in previous versions of
Visual Basic, because classes are a block level construct.
4 Module 5: Object-Oriented Programming in Visual Basic .NET
You can use access modifiers to specify the scope of the variables and
procedures in the class that you define. Visual Basic .NET retains three access
modifiers that are used in previous versions of Visual Basic and adds two more:
Protected and Protected Friend. The following table defines the five access
modifiers available in Visual Basic .NET.
Access modifier Definition
Declaring Methods
Topic Objective
To explain how to declare
methods in a class.
Lead-in n Same Syntax As in Visual Basic 6.0
The syntax for declaring
methods in a class has Public
Public Sub
Sub TestIt(ByVal
TestIt(ByVal xx As
As Integer)
Integer)
not changed in ...
...
End
End Sub
Visual Basic .NET. Sub
Public
Public Function
Function GetIt(
GetIt( )) As
As Integer
Integer
...
...
End
End Function
Function
You use the same syntax to declare a method in Visual Basic .NET that you
used in Visual Basic 6.0, as shown in the following example:
Public Class TestClass
End Class
6 Module 5: Object-Oriented Programming in Visual Basic .NET
Declaring Properties
Topic Objective
To explain how to declare
properties in a class.
n Syntax Differs from That of Visual Basic 6.0
Lead-in
The syntax for declaring Public
Public Property
Property MyData(
MyData( )) As
As Integer
Integer
class properties has Get
Get
changed significantly in Return
Return intMyData
intMyData 'Return
'Return local
local variable
variable value
value
End
End Get
Visual Basic .NET. Set
Get
Set (ByVal
(ByVal Value
Value As
As Integer)
Integer)
intMyData
intMyData == Value
Value 'Store
'Store Value
Value in
in local
local variable
variable
End
End Set
Set
End
End Property
Property
When you create a property declaration, the Visual Basic .NET Code Editor
inserts a template for the remainder of the property body.
Module 5: Object-Oriented Programming in Visual Basic .NET 7
Example
The following example shows how to declare a property called MyData of type
Integer. The Get block returns an unseen local variable called intMyData by
using a Return statement. The Set block uses the Value parameter to store the
passed-in property value to the intMyData local variable.
Private intMyData As Integer
You cannot use the Set block when defining read-only properties because the
property cannot be updated. The compiler will generate an error if you attempt
to do this.
You cannot use the Get block when defining write-only properties because the
property is not readable. The compiler will generate an error if you attempt to
do this.
8 Module 5: Object-Oriented Programming in Visual Basic .NET
Using Attributes
Topic Objective
To explain how to use
attributes.
Lead-in n Extra Metadata Supplied by Using “< >” Brackets
Attributes provide extra
information about your code.
n Supported for:
l Assemblies, classes, methods, properties, and more
n Common Uses:
l Assembly versioning, Web Services, components,
security, and custom
<Obsol
<Obsol e e ttee((""PPl leeaassee uussee mmeetthhoodd M M22 "" )) >> Publ
P u b il icc S
Sub
u b M1(
M1 ( ) )
' ' RReessuul lt tss i inn wwaarrnni inngg i inn IIDDEE wwhheenn uusseedd bbyy cclliieenntt ccooddee
End
End SubSub
Note For more information about creating custom attributes, see “Writing
Custom Attributes” in the Microsoft Visual Studio ® .NET documentation.
10 Module 5: Object-Oriented Programming in Visual Basic .NET
Example
The following example shows how to use the Obsolete attribute to warn
developers that a method can no longer be used. An optional message is
displayed in the Task List window if a developer attempts to use this method.
Using the Obsolete method will not create an error when the application is
compiled, but will generate a warning as follows:
<Obsolete("Please use method M2")> Public Sub M1( )
'Results in warning in IDE when used by client code
End Sub
Note All attributes are simply classes that inherit from the Attribute class and
provide constructors. The Obsolete class provides a single constructor that
takes a string as the parameter.
Module 5: Object-Oriented Programming in Visual Basic .NET 11
Overloading Methods
Topic Objective
To introduce the concept
and syntax of overloading in
Visual Basic .NET. n Methods with the Same Name Can Accept Different
Parameters
Lead-in
Overloading is a powerful Public
Public Function
Function Display(s
Display(s As As String)
String) As
As String
String
MsgBox("String:
MsgBox("String: "" && s)
object-oriented feature that Return "String"
s)
Return "String"
allows multiple methods to End
End Sub
Sub
have the same name but Public
Public Function
Function Display(i
Display(i As
As Integer)
Integer) As
As Integer
Integer
accept different parameters. MsgBox("Integer:
MsgBox("Integer: "" && i)
i)
Return
Return 11
End
End Function
Function
The following example shows how to overload a method. This code allows
different types of information (string, integers, and so on) to be displayed by
calling the Display method of a class and passing in different parameters.
When you call the Display method, the parameters you specify determine
which overloaded method will be called.
Without using overloading, you need two different methods , such as
DisplayString and DisplayInteger, to accept the different types of parameters
in the preceding example.
Note If the Option Strict compiler option is on, you must explicitly declare
values as specific types when passing them to the overloaded methods as
parameters, and the compiler can identify which instance of the method to call.
If Option Strict is off and a generic variable (such as Object ) is passed as a
parameter, the decision of which instance of the method to call is left until run
time. For more information about overload resolution, see “Procedure
Overloading” in the Visual Studio .NET documentation.
Module 5: Object-Oriented Programming in Visual Basic .NET 13
Using Constructors
Topic Objective
To explain the concept and
syntax of class constructors.
Lead-in n Sub New Replaces Class_Initialize
Visual Basic .NET allows
you to create class n Executes Code When Object Is Instantiated
constructors. Public
Public Sub
Sub New(
New ( ))
'Perform
'Perform simple
simple initialization
initialization
intValue
intValue == 11
End
End Sub
Sub
In Visual Basic 6.0, you place initialization code in the Class_Initialize event
Delivery Tip of your class. This code is executed when the object is instantiated, and you can
This is an animated slide. It
begins by showing the first use it to set initial values of local variables, to open resources, or to instantiate
example. Click the slide to other objects.
reveal an example of
In Visual Basic .NET, you control the initialization of new objects by using
overloading.
procedures called constructors. The Sub New constructor replaces the
Class_Initialize event and has the following features:
n The code in the Sub New block will always run before any other code in a
class.
n Unlike Class_Initialize , the Sub New constructor will only run once: when
an object is created.
n Sub New can only be called explicitly in the first line of code of another
constructor, from either the same class or a derived class using the MyBase
keyword.
The change in Visual Basic .NET from the Class_Initialize event to the Sub
New constructor means you can overload the New subroutine and create as
many class constructors as you require. This is useful if you want to initialize
your object when you instantiate it. To do this in Visual Basic 6.0, you must
call methods or properties after the object is created.
14 Module 5: Object-Oriented Programming in Visual Basic .NET
Overloading Constructors
You can overload constructors just as you can overload any other method in a
class. However, you cannot us e the Overloads keyword when overloading
constructors. The following example shows how to overload the New
subroutine and create multiple class constructors:
Public Sub New( ) 'Perform simple initialization
intValue = 1
End Sub
Using Destructors
Topic Objective
To explain destructors
and their syntax in
Visual Basic .NET. n Sub Finalize Replaces Class_Terminate Event
Lead-in
Destructors are used to n Use to Clean Up Resources
destroy objects in n Code Executed When Destroyed by Garbage Collection
Visual Basic .NET.
l 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
In Visual Basic .NET, you can control what happens during the destruction of
objects by using procedures called destructors.
The new Finalize destructor replaces the Class_Terminate event found in
Delivery Tip previous versions of Visual Basic. This subroutine is executed when your object
Point out that the Finalize is destroyed, and you can use it to clean up open resources, such as database
method should only be used connections, or to release other objects in an object model hierarchy.
where necessary so it
doesn’t cause unnecessary The following example shows how to use the Finalize destructor:
processing during object
Protected Overrides Sub Finalize( )
clean-up.
'Can close connections of other resources
conn.Close
End Sub
Note You will learn about the Overrides keyword in the Inheritance lesson of
this module.
In this lesson, you will learn about creating and destroying objects. After
completing this lesson, you will be able to:
n Instantiate and initialize objects.
n Explain the role that garbage collection plays in the object life cycle.
n Use the Dispose method to destroy an object and safely clean up its
resources.
Module 5: Object-Oriented Programming in Visual Basic .NET 17
'Declare,
‘declare,
‘declare, instantiate
'Declare, instantiate && initialize
initialize using
using default
default constructor
constructor
Dim
Dim c2
c2 As
As TestClass
TestClass == New
New TestClass(
TestClass()
TestClass()))
TestClass(
'Declare,
‘declare,
‘declare, instantiate
'Declare, instantiate && initialize
initialize using
using default
default constructor
constructor
Dim
Dim c3
c3 As
As New
New TestClass(
TestClass
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)
You can now instantiate and initialize objects in one line of code. This means
you can write simpler and clearer code that can call different class constructors
for multiple variables.
Example 2
The following example shows how to declare, instantiate, and initialize an
object in one statement. The default constructor for the class will be executed.
'Declare, instantiate & initialize using default constructor
Delivery Tip Dim c2 As TestClass = New TestClass( )
Ensure that students are
aware of the differences
between the behavior of the
following statement in
Visual Basic .NET as
opposed to previous
versions of Visual Basic:
Dim x As New TestClass
18 Module 5: Object-Oriented Programming in Visual Basic .NET
Example 3
The following example performs the same functionality as Example 2. It looks
similar to code from previous versions of Visual Basic, but behaves quite
differently.
'Declare, instantiate & initialize using default constructor
Dim c3 As New TestClass
Example 4
The following examples show how to declare, instantiate, and initialize objects
in single statements. Both statements call alternative constructors for the class.
'Declare, instantiate & initialize using alternate constructor
Dim c4 As New TestClass(10)
Dim c5 As TestClass = New TestClass(10)
Module 5: Object-Oriented Programming in Visual Basic .NET 19
Garbage Collection
Topic Objective
To explain garbage
collection and how it affects
object lifetime. n Background Process That Cleans Up Unused Variables
Lead-in n Use x = Nothing to Enable Garbage Collection
Garbage collection
significantly alters how n Detects Objects or Other Memory That Cannot Be
objects are destroyed. Reached by Any Code (Even Circular References!)
n Calls Destructor of Object
l No guarantee of when this will happen
l Potential for resources to be tied up for long periods of
time (database connections, files, and so on)
l You can force collection by using the GC system class
Because of the potential time delay created by garbage collection, you may
Delivery Tip
want to create a standard method called Dispose for your class. Many
This is an animated slide. It
Visual Studio .NET objects use this method to clean up resources.
begins by showing the
Dispose example. Click the When client code has no further need for an object’s resources, it can directly
slide to reveal the client
call code placed in the Dispose method of the object. If the client code does not
code example.
call the Dispose method explicitly before garbage collection occurs, the
Point out that you must be Finalize method of the class can also call the Dispose method. However, note
cautious when executing that you may cause an exception if you attempt to run the Dispose code twice.
code in the Finalize method An exception can occur if you have already closed or released an object and do
if resources have been not test to determine whether it still exists in the second execution of the
cleaned up in a Dispose Dispose code.
method.
Example
The following simple example shows how to create a Dispose method to
manually release resources:
'Class code
Public Sub Dispose( )
'Check that the connection is still open
...
conn.Close 'Close a database connection
End Sub
'Client code
Dim x as TestClass = New TestClass( )
...
x.Dispose( ) 'Call the object's dispose method
22 Module 5: Object-Oriented Programming in Visual Basic .NET
Note You will learn how to implement interfaces in the Interfaces lesson of
this module.
If you completely clean up your object in a Dispose method (whether you use
IDisposable or not), garbage collection does not need to execute your Finalize
method. You can disable the execution of the Finalize method by calling the
SuppressFinalize method on the GC object, as shown in the following
example. This method accepts a single argument that is a reference to the object
that should not have its Finalize method called. In Visual Basic .NET, this is
done with the Me keyword.
In the following example, if the client code called the Dispose method directly,
the connection would be closed and the Finalize method would not be called by
garbage collection. If the client did not call the Dispose method, the Finalize
method will still execute when garbage collection destroys the object.
'Class code
Public Sub Dispose( )
'Check that the connection is still open
...
conn.Close 'Close a database connection
GC.SuppressFinalize(Me)
End Sub
In this demonstration, you will learn how to define a simple class that uses
Delivery Tip
multiple constructors. You will also learn how to instantiate and use the class
The step-by-step
from within client code.
instructions for this
demonstration are in the
instructor notes for this
module.
24 Module 5: Object-Oriented Programming in Visual Basic .NET
Prerequisites
Before working on this lab, you should be familiar with creating classes in
Visual Basic .NET.
Scenario
In this lab, you will begin creating the Cargo system. You will create the
Customer class and a test application to instantiate, initialize, and test the class.
Exercise 1
Defining the Customer Class
In this exercise, you will define the Customer class. The starter project
contains several forms that you will use to test your Customer class.
2. Add the following public properties, and use these to access the private
variables created in the previous step.
Property name Read/Write access Data type
CustomerID Read-only Integer
FirstName Read-write String
LastName Read-write String
Email Read-write String
Password Read-write String
Address Read-write String
Company Read-write String
2. On the File menu, point to Open, and click File. In the Files of type list,
click Text Files. Click Code.txt, and then click Open.
3. Locate the LogOn code in Code.txt. Copy the procedure code to the LogOn
method of the Customer class.
4. Locate the AddCustomer code in Code.txt. Copy the procedure code to the
AddCustomer method of the Customer class.
Exercise 2
Testing the LogOn Procedure
In this exercise, you will test the LogOn procedure from a simple form.
Exercise 3
Testing Customer Retrieval
In this exercise, you will test the parameterized constructor that retrieves the
customer details from a simple form. A sales agent who needs full access to the
customer’s information could use this type of form.
txtEmail Email
txtPassword Password
txtFName FirstName
txtLName LastName
txtAddress Address
txtCompany Company
Exercise 4
Testing the AddCustomer Procedure
In this exercise, you will test the AddCustomer procedure from a simple form.
strEmail txtEmail.Text
strPassword txtPassword.Text
strFName txtFName.Text
strLName txtLName.Text
strCompany txtCompany.Text
strAddress txtAddress.Text
u Inheritance
Topic Objective
To provide an ov erview of
the topics covered in this
lesson. n What Is Inheritance?
Lead-in
In this lesson, you will learn n Overriding and Overloading
about inheritance. n Inheritance Example
n Shadowing
n Using the MyBase Keyword
n Using the MyClass Keyword
In this lesson, you will learn how to implement class inheritance. After
Delivery Tip completing this lesson, you will be able to:
Inform students that
although inheritance is an n Inherit from an existing class.
important new feature of
Visual Basic .NET, you can n Override and overload some base class methods in a derived class.
continue to create classes n Use the MyBase keyword to access the base class from a derived class.
without inheritance, as in
previous versions of n Use the MyClass keyword to ensure that you call the correct class.
Visual Basic.
32 Module 5: Object-Oriented Programming in Visual Basic .NET
What Is Inheritance?
Topic Objective
To explain the keywords
and syntax for class n Derived Class Inherits from a Base Class
inheritance.
n Properties, Methods, Data Members, Events, and Event
Lead-in Handlers Can Be Inherited (Dependent on Scope)
Inheriting a class allows you
to use the features of a base n Keywords
class without rewriting the
code. l Inherits – inherits from a base class
l NotInheritable – cannot be inherited from
l MustInherit – instances of the class cannot be created;
must be inherited from as a base class
l Protected – member scope that allows use only by
deriving classes
In Visual Basic .NET , you can use inheritance to derive a class from an existing
base class. The derived class can inherit all the base class properties, methods,
Delivery Tip data members, events, and event handlers, making it easy to reuse the base class
Point out that inheritance code throughout an application.
can be used to create highly
reusable code. However, The Inherits Keyword
many applications do not
need inheritance and can The following example shows how to use the Inherits keyword to define a
perform perfectly well derived class that will inherit from an existing base class:
without it. Make clear that if
Public Class DerivedClass
inheritance is used, students
should not create complex Inherits BaseClass
hierarchies that will become ...
unmanageable. End Class
Note The derived class is also known as a subclass, and the base class is
known as a superclass in Unified Modeling Language (UML) terminology.
34 Module 5: Object-Oriented Programming in Visual Basic .NET
When a derived class inherits from a base class, it inherits all the functions,
Delivery Tip
subroutines, and properties of the base class, including any implementation in
Point out that examples are
shown in the student notes the methods. Occasionally you may want to create implementation code
but that a fuller example will specific to your derived class rather than using the inherited methods. This is
be discussed on the next known as overriding. You can also overload methods defined in the base class
slide. with the Overloads keyword.
Overriding
Use the following keywords to create your own implementation code within a
derived class:
n Overridable
To create your own special implementation of the derived class, specify the
Overridable keyword in a base class member definition for a function,
subroutine, or property, as shown in the following example:
Public Overridable Sub OverrideMethod( )
MsgBox("Base Class OverrideMethod")
End Sub
n MustOverride
To create a base class member that must be overridden in all derived classes,
define the member with the MustOverride keyword. Only the member
prototype can be created in the base class, with no implementation code.
You can only use this keyword in a base class that is marked as
MustInherit. The following example shows how to define a method that
must be overridden:
Public MustOverride Sub PerformAction( )
MustOverride methods are useful in base classes because they allow you to
define baseline functionality without locking in implementation details that
can make them difficult to extend.
Module 5: Object-Oriented Pro gramming in Visual Basic .NET 35
n Overrides
To specify that a derived class method overrides the implementation of the
base class method, use the Overrides keyword. If the base class method that
is being overridden is not marked as Overridable, a compile-time error will
occur. The method signature must exactly match the method being
overridden, except for the parameter names. The following example shows
how to declare a derived class method that overrides the base class
implementation:
Public Overrides Sub OverrideMethod( )
MsgBox("Derived Class OverrideMethod")
End Sub
Note You can override methods by selecting (Overrides) in the Class Name
drop-down list in the IDE, and then selecting the method you want to
override.
n NotOverridable
Base class members without the Overridable keyword are, by default, not
overridable. However, if a base class member is marked as overridable, then
the member will be overridable in any derived classes based on the
immediate deriving class. To prevent this behavior, mark the overridden
method in the derived class as NotOverridable. This will stop subsequent
inheritance from overriding the method.
The following example shows how to declare a derived class method that
overrides the base class implementation but does not allow any further
overriding:
Public NotOverridable Overrides Sub OverrideMethod( )
MsgBox("Derived Class OverrideMethod")
End Sub
Overloading
You can create a method in a derived class that overloads a method defined in a
base class by using the Overloads keyword. Just as for overloading methods
within the same class, the method signatures must include different parameters
or parameter types. The following example shows how to overload a method
from a base class:
Public Overloads Sub Other(ByVal i As Integer)
MsgBox("Overloaded CannotOverride")
End Sub
Note that the base class method does not need to be marked as Overridable to
be overloaded.
36 Module 5: Object-Oriented Programming in Visual Basic .NET
Inheritance Example
Topic Objective Public
Public Class
Class BaseClass
BaseClass
To provide an example of Public
Public Overridable Sub
Overridable Sub OverrideMethod(
OverrideMethod( ))
inheritance. MsgBox("Base
MsgBox("Base OverrideMethod")
OverrideMethod")
End
End Sub
Lead-in Sub
Public
Public Sub
Sub Other(
Other( ))
Let’s look at a full example MsgBox("Base
MsgBox("Base Other
Other method
method –– not
not overridable")
of inheritance. End
overridable")
End Sub
Sub
End
End Class
Class
Public
Public Class
Class DerivedClass
DerivedClass
Inherits
Inherits BaseClass
BaseClass
Public
Public Overrides
Overrides Sub
Sub OverrideMethod(
OverrideMethod( ))
MsgBox("Derived
MsgBox("Derived OverrideMethod")
OverrideMethod")
End
End Sub
Sub
End
End Class
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
x.OverrideMethod 'Displays
'Displays "Derived
"Derived OverrideMethod"
OverrideMethod"
The following table explains the methods used in the preceding code.
Calling Code
The preceding example defines and instantiates a DerivedClass variable. The
following example shows how to call all the individual methods for the derived
class. The results are shown as comments in the code.
Shadowing
Topic Objective
To describe the concept of
shadowing and explain how n Hides Base Class Members, Even If Overloaded
to shadow a method in a
Class
Class aBase
derived class. aBase
Public
Public Sub
Sub M1(
M1( )) 'Non-overridable
'Non-overridable by
by default
default
Lead-in ...
...
End
End Sub
Visual Basic .NET allows End
Sub
End Class
Class
you to shadow a method in Class
a derived class. Class aShadowed
aShadowed
Inherits
Inherits aBase
aBase
Public
Public Shadows
Shadows Sub
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
End Class
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
'No error
error
When a derived class inherits from a base class, it can either override a method
on the base class or shadow it. Overriding replaces the existing method based
on the method name and signature. Shadowing effectively hides the method in
the base class, based solely on the method name. This means shadowing a
method also hides any overloaded methods within the base class. You can
shadow a method regardless of whether the base method is specified as
overridable.
To learn how shadowing works, consider an example of a derived class that
shadows a method from the base class. The method in the base class has not
been specified as overridable.
Module 5: Object-Oriented Programming in Visual Basic .NET 39
The following example shows a base class that defines a single method called
M1. The derived class declares an M1 method that automatically shadows the
base class method and accepts a single argument. The client code can only
access the shadowed method that accepts the argument, and an error will be
generated if it attempts to access the base class method.
Class aBase
Public Sub M1( ) 'Non-overridable by default
...
End Sub
End Class
Class aShadowed
Inherits aBase
Public Shadows Sub M1(ByVal i As Integer)
'Clients can only see this method
...
End Sub
End Class
'Client Code
Dim x As New aShadowed( )
x.M1( ) 'Generates an error because method is hidden
x.M1(20) 'No error
40 Module 5: Object-Oriented Programming in Visual Basic .NET
You can use the MyBase keyword to access the immediate base class from
which a derived class is inheriting. When using MyBase, you should be aware
of some limitations:
n It refers only to the immediate base class in the hierarchy. You cannot use
Delivery Tip MyBase to gain access to classes higher in the hierarchy.
Calling the constructor of a
base class is a common use n It allows access to all of the public, protected, or friend members of the base
of the MyBase keyword. class.
n It is not a real object, so you cannot assign MyBase to a variable.
If a derived class is overriding a method from a base class but you still want to
execute the code in the overridden method, you can use MyBase. This is a
common practice for constructors and destructors. The following example
shows how to use the MyBase keyword to execute a method as implemented in
the base class:
Public Class DerivedClass
Inherits BaseClass
Public Sub New()
MyBase.New() 'Call the constructor of the base class
intValue = 1
End Sub
Public Overrides Sub OverrideMethod()
MsgBox("Derived OverrideMethod")
MyBase.OverrideMethod() 'Call the original method
End Sub
End Class
Module 5: Object-Oriented Programming in Visual Basic .NET 41
Dim
Dim xx As
As DerivedClass
DerivedClass == New
New DerivedClass(
DerivedClass( ))
x.Other(
x.Other( ) )
You can use the MyClass keyword to ensure that a base class implementation
Delivery Tip
of an overridable method is called, rather than that of a derived class. When
Point out the important note
using MyClass, you should be aware of some limitations:
in the student notes
regarding the differences n It allows access to all of the public, protected, or friend members of the
between the MyClass and deriving class.
Me keywords.
n It is not a real object, so you cannot assign MyClass to a variable.
Example
The following example shows how to call a base class method from a derived
class by using the MyClass keyword:
Public Class BaseClass
Public Overridable Sub OverrideMethod( )
MsgBox("Base OverrideMethod")
End Sub
Output
The output from the execution of the preceding code is as follows:
Base OverrideMethod
Flow of Execution
The code in the example is executed as follows:
1. The Other method is called on the DerivedClass object, but because there
is no implemented code in the derived class, the base class code is executed.
2. When the MyClass.OverrideMethod call is executed, the
OverrideMethod subroutine is implemented in the base class.
3. Execution returns to the client code.
Demonstration: Inheritance
Topic Objective
To demonstrate class
inheritance.
Lead-in
This demonstration
examines how to create and
use class inheritance.
In this demonstration, you will see how to define a base class with a mixture of
Delivery Tip
overridable and non-overridable methods. You will see how to derive a class
The step-by-step
that inherits from the base class, and how to use the MyBase keyword.
instructions for this
demonstration are in the
instructor notes for this
module.
44 Module 5: Object-Oriented Programming in Visual Basic .NET
u Interfaces
Topic Objectiv e
To provide an overview of
the topics covered in this
lesson. n Defining Interfaces
Lead-in
In this lesson, you will learn n Achieving Polymorphism
about interfaces and
polymorphism.
In this lesson, you will learn how to use interfaces to achieve polymorphism.
Delivery Tip After completing this lesson, you will be able to:
This lesson assumes some
knowledge about interfaces n Define an interface by using the Interface keyword.
and polymorphism.
n Add member signatures that define the properties, methods, and events that
The topic is not covered your interface supports.
extensively because n Implement an interface by using the Implements keyword.
interfaces and
polymorphism are not new
to Visual Basic .NET. You
should ensure that students
are aware of additional
appropriate information.
Module 5: Object-Oriented Programming in Visual Basic .NET 45
Defining Interfaces
Topic Objective
To explain how to
create interfaces in n Interfaces Define Public Procedure, Property, and Event
Visual Basic .NET. Signatures
Lead-in n Use the Interface Keyword to Define an Interface Module
Interfaces are a new and
powerful feature of n Overload Members as for Classes
Visual Basic .NET. 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
n Use the Inherits Keyword in an Interface to Inherit From
Other Interfaces
Example
The following example shows how to define an interface that includes three
method signatures, two of which are overloaded:
Interface IMyInterface
Function Method1(ByRef s As String) As Boolean
Sub Method2( )
Sub Method2(ByVal i As Integer)
End Interface
An interface can also inherit another interface if you use the Inherits keyword
before any member signatures are defined. If an interface is inherited from the
above example, it will contain all of the base interface signatures, in addition to
those defined in the new interface definition.
Module 5: Object-Oriented Programming in Visual Basic .NET 47
Achieving Polymorphism
Topic Objective
To explain how to use
polymorphism in n Polymorphism
Visual Basic .NET.
l Many classes provide the same property or method
Lead-in
Visual Basic .NET combines l A caller does not need to know the type of class the
a traditional use of object is based on
interfaces— to create
polymorphism— with the n Two Approaches
new class inheritance
features. l Interfaces
Class implements members of interface
Same approach as in Visual Basic 6.0
l Inheritance
Derived class overrides members of base class
Example
The following example shows how to implement polymorphism in
Visual Basic .NET. As you examine this code, note the following:
n The IPerson interface defines two member signatures: LastName and
Display.
n The Employee class implements the IPerson interface and both of its
members.
n By using the Implements keyword for each individual method, you can
specify your own name for the method and it will still be executed if a client
application requests the original name of the interface.
Inheritance
Another way to ac hieve polymorphism with Visual Basic .NET is to use class
inheritance. A base class can be created that contains member signatures and
that optionally contains implementation code that can be inherited in a derived
class. The derived class must then override the individual methods with its own
implementation code, achieving unique functionality while retaining a common
method signature.
In this demonstration, you will learn how to create an interface and implement
Delivery Tip it to achieve polymorphism in two separate classes.
The step-by-step
instructions for this
demonstration are in the
instructor notes for this
module.
Module 5: Object-Oriented Programming in Visual Basic .NET 51
In this lesson, you will learn how to work with classes. After completing this
lesson, you will be able to:
n Use shared data members to share data across class instances.
n Use shared procedure members.
n Define and handle class events.
n Use delegates in event handling.
n Describe how structures differ from classes.
52 Module 5: Object-Oriented Programming in Visual Basic .NET
SavingsAccount
SavingsAccount. .I Innt teer reesst R t Raat e t e == 0.0030.003
Di
Di mm acct
acct1 1 AsAs New New SavingsAccount
SavingsAccount("Joe ("Joe Howard", Howard", 10000) 10000)
MMss g
gBBo
o xx (( a
a cc cc tt 11..C
Caallccuul laatteeI Innt teer reesst ,t , , , " I" nI nt et er er es ts t f of ro r " "& &a cacctc1t.1N. a
Nm e)
a me)
In Visual Basic 6.0, you can share data among objects by using a module file
and a global variable. This approach works, but there is no direct link between
Delivery Tip the objects and the data in the module file, and the data is available for anyone
This is an animated slide. It
to access.
begins by showing the
Shared example code. Click In Visual Basic .NET, you can use shared data members to allow multiple
the slide to reveal an instances of a class to refer to a single instance of a class-level variable. You
example of client code.
can use shared members for counters or for any common data that is required
by all instances of a class.
An advantage of shared data members is that they are directly linked to the
class and can be declared as public or private. If you declare data members as
public, they are accessible to any code that can access the class. If you declare
the data members as private, provide public shared properties to access the
private shared property.
Module 5: Object-Oriented Programming in Visual Basic .NET 53
The following example shows how you can use a shared data member to
maintain interest rates for a savings account. The InterestRate data member of
the SavingsAccount class can be set globally regardless of how many instances
of the class are in use. This value is then used to calculate the interest on the
current balance.
Class SavingsAccount
Public Shared InterestRate As Double
The following code shows how a client application can use the
SavingsAccount class in the previous example. As you examine this code, note
the following:
n The InterestRate can be set before and after any instances of the
SavingsAccount object are created.
n Any changes to the InterestRate will be seen by all instances of the
SavingsAccount class.
Sub Test( )
SavingsAccount.InterestRate = 0.003
The following example shows how to implement a public shared property for a
private shared data member:
Class SavingsAccount
Private Shared InterestRate As Double
The following code shows how a client application can use the shared property
in the previous example:
SavingsAccount.Rate = 0.003
Module 5: Object-Oriented Programming in Visual Basic .NET 55
'Client
'Client code
code
MsgBox(TestClass.GetComputerName(
MsgBox(TestClass.GetComputerName( ))
))
You can use shared procedure members to design functions that can be called
Delivery Tip without creating an instance of the class. Shared procedures are particularly
Point out that this feature is
often used for library useful for creating library routines that other applications can easily access.
routines. This concept is similar to the GlobalMultiUse and GlobalSingleUse classes
used in Visual Basic 6.0.
As described in the previous topic, shared members can only access data that is
marked as Shared. For example, a shared method cannot access a module level
variable that is marked as either Dim, Private, or Public.
Example
The following example shows how a commonly used function, such as
GetComputerName, can be created as a shared procedure member so that a
client application can easily use it. The client only needs to reference the
method prefixed by the class name because no instance of the class is required.
'TestClass code
Public Shared Function GetComputerName( ) As String
...
End Function
'Client code
MsgBox(TestClass.GetComputerName( ))
56 Module 5: Object-Oriented Programming in Visual Basic .NET
Event Handling
Topic Objective
To introduce event-handling
options that are new in n Defining and Raising Events: Same As Visual Basic 6.0
Visual Basic .NET.
n WithEvents Keyword: Handles Events As in Visual Basic 6.0
Lead-in l In Visual Basic .NET, works with Handles keyword to specify
Visual Basic .NET provides method used to handle event
some powerful new event-
handling enhancements. n 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
AddHandler y.anEvent,
y.anEvent, AddressOf
AddressOf HandleEvent
HandleEvent
...
...
Sub
Sub HandleEvent(ByVal
HandleEvent(ByVal ii As
As Integer)
Integer)
...
...
End
End Sub
Sub
n RemoveHandler Keyword: Disconnects from Event Source
As a Visual Basic developer, you are familiar with creating events. However,
Visual Basic .NET provides powerful new event handling features with the
addition of the Handles, AddHandler and RemoveHandler keywords.
Example
The following example shows how to define and raise an event:
'TestClass code
Public Event anEvent(ByVal i As Integer)
Example
The following example shows how you can use WithEvents in conjunction
with the new Handles keyword to link an event with a handler.
'Client code
Dim WithEvents x As TestClass
Dim WithEvents y As TestClass
Syntax
The syntax for AddHandler is shown below.
Example
The following example shows a single method handler called HandleEvent
being used for two instances of TestClass:
Dim x As New TestClass( ), y As New TestClass( )
Syntax
The syntax for RemoveHandler is shown below.
RemoveHandler object.EventName, AddressOf methodName
In this demonstration, you will learn how to define and raise events in a class
Delivery Tip and how to handle them in client code.
The step-by-step
instructions for this
demonstration are in the
instructor notes for this
module.
60 Module 5: Object-Oriented Programming in Visual Basic .NET
The common language runtime supports objects called delegates that can call
the methods of other objects dynamically. Delegates are sometimes described
as type-safe function pointers because they are similar to the function
pointers used in other programming languages. Unlike function pointers,
Visual Basic .NET delegates are a reference type based on the class
System.Delegate and can reference both shared methods (methods that can be
called without a specific instance of a class) and instance methods. Delegates
provide the same flexibility as function pointers in Microsoft Visual C++ ®
without the risk of corrupted memory because they are type-safe, secure,
managed objects.
Delegates are useful when you need an intermediary between a calling
procedure and the procedure being called. For example, you might want an
object that raises events to be able to call different event handlers under
different circumstances. Unfortunately, the object raising events cannot
know ahead of time which event handler is handling a specific event.
Visual Basic .NET allows you to dynamically associate event handlers with
events by creating a delegate for you when you use the AddHandler statement.
At run time, the delegate forwards calls to the appropriate event handler.
Module 5: Object-Oriented Programming in Visual Basic .NET 61
Using Delegates
Topic Objective
To provide an example of
how to use delegates in
event handling. n Delegate Keyword Declares a Delegate and Defines
Lead-in Parameter and Return Types
Let’s look at an example of
how you can use delegates
in event handling. Delegate
Delegate Function
Function CompareFunc(
CompareFunc( __
ByVal
ByVal xx As
As Integer,
Integer, ByVal
ByVal yy As
As Integer)
Integer) As
As Boolean
Boolean
You use the Delegate keyword to declare a delegate function signature that
defines the parameter and return types. Only methods that have the same
function parameter and return types can be used with a particular delegate
object.
Example
To learn how delegates work, consider an example that shows how to declare a
delegate function signature, create methods to accept the parameter types you
have defined, and call the functions by using the delegate object. The final part
of this example shows how to use the delegate to perform a bubble sort.
Calling Methods
After you create the necessary functions, you can write a procedure to call these
two functions by using a delegate object as follows:
Sub SimpleTest( )
Dim delDelegate As CompareFunc
For I = 0 To Ubound(intArray)
Value = intArray(I)
For J = I + 1 To Ubound(intArray)
If delDelegate.Invoke(intArray(J), Value) Then
intArray(I) = intArray(J)
intArray(J) = Value
Value = intArray(I)
End If
Next J
Next I
End Sub
Module 5: Object-Oriented Programming in Visual Basic .NET 63
The following code shows how to call the bubble sort procedure:
Sub TestSort( )
Dim a( ) As Integer = {4, 2, 5, 1, 3}
Classes and structures are similar in several ways: both can define data
members, properties, and methods. However, classes provide some advanced
features that developers can use.
Classes Structures
Prerequisites
Before working on this lab, you should be familiar with inheritance in
Visual Basic .NET.
Scenario
In this lab, you will continue creating the Cargo system. You will create the
Package base class, the SpecialPackage derived class, and the test application.
Some of the code has been created for you.
Exercise 1
Completing the SpecialPackage Class
In this exercise, you will examine the pre-written Package class and complete
the partially written SpecialPackage class. You will inherit from the Package
class, and override some of its methods.
This will create the relationship between the Package base class and the
derived class SpecialPackage.
Module 5: Object-Oriented Programming in Visual Basic .NET 67
3. After the property value assignments, use the MsgBox function to display
the message “Special instructions added”.
4. Return the PackageID as the return value of the CreatePackage method.
Exercise 2
Retrieving Packages
In this exercise, you will write the calling code for the Retrieve button that
calls either a Package or a SpecialPackage object. You will then test your code
by entering some values into the Package form.
Exercise 3
Creating Packages
In this exercise, you will write the calling code for the New button that creates
either a Package or SpecialPackage object. You will then test your code by
entering some values into the Package form.
3. Store the return of the CreatePackage method in the Text property of the
txtID box. (Use the CStr function to convert the Integer to a String.)
DeliveryID 43
Description Heart Transplant
Instructions Deliver to Joe Howard
Dimensions NA
Weight NA
Value 0
SpecialPackage checkbox Checked
ExtraInstructions Speed is essential
OxygenRequired checkbox Unchecked
Temperature 20
TimeLimit 2 hours
Exercise 4
Deleting Packages
In this exercise, you will write the calling code for the Delete button that
deletes either a Package or SpecialPackage object. You will then test your
code by entering some values into the Package form.
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. n Defining Classes
Lead-in
The review questions cover n Creating and Destroying Objects
some of the key concepts n Inheritance
taught in the module.
n Interfaces
n Working with Classes
1. Create code that defines multiple constructors for a Person class. The first
constructor will not take any arguments. The second will take two string
values: FirstName and LastName.
Class Person
Sub New( )
'Default constructor
End Sub
Sub New(ByVal FirstName As String, _
ByVal LastName As String)
'Second constructor
End Sub
End Class
4. What is a potential problem that may result from the following class code
sample? How can you rewrite the code to resolve the problem?
Class Person
Private Sub Save( )
'Save the local data in a database
End Sub
Sub Dispose( )
Save( )
End Sub
The Dispose method can be called directly from a client and might be
called again when the object is destroyed by garbage collection. This
would result in the Save method being called twice, which may create
data inconsistencies.
To avoid this, use the SuppressFinalize method of the GC class to stop
the Finalize method being called after Dispose. Add the line
"GC.SuppressFinalize()" in the Dispose method after the Save line as
follows):
Sub Dispose()
Save()
GC.SuppressFinalize()
End Sub
76 Module 5: Object-Oriented Programming in Visual Basic .NET
5. You can create an interface explicitly in Visual Basic .NET. True or false?
If false, explain why.
True. You can create an interface explicitly by using the
Interface…End Interface statement block.
Module TestCode
Sub Main( )
Dim x As New Person( )
AddHandler x.NameChanged, AddressOf HandleIt
x.ChangeName("Jeff")
End Sub
The code will not compile correctly because the signature of the event
does not match the signature of the delegate in the AddHandler
statement.