Professional Documents
Culture Documents
Oriented Programming
in Visual Basic .NET
Contents
Overview 1
Multimedia: Introduction to Object-
Oriented Concepts 2
Lesson: Understanding Classes 3
Lesson: Working with Classes 8
Lesson: Using Shared Members 21
Lesson: Inheritance, Polymorphism, and
Namespaces 27
Review 35
Lab 7.1: Creating a Derived Class 37
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 7: Object-Oriented Programming in Visual Basic .NET iii
Instructor Notes
Presentation and This module provides students with an explanation of how to create and use
practices: classes. The module explains the concepts of abstraction, encapsulation,
135 minutes instantiation, initialization, and constructors and destructors. This module also
describes inheritance, polymorphism, and namespaces.
Lab:
30 minutes After completing this module, students will be able to:
! Explain object-oriented programming concepts, including class, abstraction,
encapsulation, and object.
! Use the Object Browser to examine available programming elements,
including classes and objects.
! Create a new class, including its methods, properties, and data members
with appropriate access levels.
! Create and use an instance of a class, including instance and shared data
members, and shared and non-shared methods.
! Explain how constructors and destructors work.
! Explain inheritance, polymorphism, and namespaces.
Required materials To teach this module, you need the following materials:
! Microsoft® PowerPoint® file 2559B_07.ppt
! Multimedia animation file 2559B_Basic OOP Concepts.htm
Review
The review questions are mostly based on conceptual understanding and on
procedures that were covered thoroughly in the module. You can use a
discussion format to answer the questions so that everyone gets the benefit of
knowing the right answers.
1. It is important for students to recognize the process of abstraction.
2. It is important for students to recognize the process of encapsulation.
3. This question provides a chance to write the code that adds a new project
and adds an instance data member and method to the code.
4. This question provides a chance to write the code to create a new class and
add a private data member.
5. This question provides a review of how to initialize and un-initialize
objects.
6. Use this question to reinforce the concept of inheritance.
Overview
Write
! Understanding Classes
Create
Debug
Interface Code
and Deploy
! Working with Classes
Use Visual
Studio .NET
! Using Shared Members
! Inheritance,
Access Polymorphism, and
Data Debug
and Deploy
Namespaces
st r action
ab
class a tion
ps ul
enca
t
objec
Lesson objectives After completing this lesson, you will be able to:
! Describe classes and objects.
! Explain the role of abstraction and encapsulation in creating classes.
! Use the Object Browser to examine classes, objects, and other programming
elements.
4 Module 7: Object-Oriented Programming in Visual Basic .NET
What Is a Class?
What Is an Object?
Object
Object
123
245
245
Objects Members
Members
Objects
Pane Pane
Pane
Pane
Description
Description
Pane
Pane
Namespace Module
Class Structure
8 Module 7: Object-Oriented Programming in Visual Basic .NET
Lesson objectives After completing this lesson, you will be able to:
! Create a new class.
! Add instance data members to a new class.
! Add methods to a new class.
! Add properties to a new class.
! Create an object.
! Use constructors to initialize new objects.
! Use destructors to un-initialize objects.
Module 7: Object-Oriented Programming in Visual Basic .NET 9
End
End Class
Class
End Class
10 Module 7: Object-Oriented Programming in Visual Basic .NET
End
End Class
Class
Keyword
Keyword Definition
Definition
Public
Public Accessible
Accessibleeverywhere
everywhere
Private
Private Accessible
Accessibleonly
onlywithin
withinthe
thetype
typeitself
itself
Accessible
Accessibleonly
onlyby
byclasses
classeswhich
whichinherit
inheritfrom
fromthe
the
Protected
Protected class
class
Me keyword You can also refer to the data member balance by using the Me keyword, as
shown in the following example:
Me.balance
Private
Private balance
balance As
As Double
Double
Public
Public Sub
Sub Deposit(ByVal
Deposit(ByVal amount
amount As
As Double)
Double)
balance += amount
balance += amount
End
End Sub
Sub
End
End Class
Class
In this example, the Deposit method is public so that the users of this class can
deposit money into an account by using the Deposit method.
Overloading methods Method overloading occurs when a class contains two or more methods with
the same name but different signatures. An example of an overloaded method is
the MessageBox.Show method. The Show method provides twelve overloads.
These overloads make the method more flexible for users of the method.
To overload a method, use the Overloads keyword. The Overloads keyword
declares a property or method with the same name as an existing member, but
with a parameter list that is different from the original member.
The following example shows an overloaded method named Execute. The first
Execute method does not take any parameters. The second one takes a string as
a parameter.
Public Overloads Sub Execute( )
...
End Sub
Public Overloads Sub Execute(ByVal connection As String)
...
End Sub
12 Module 7: Object-Oriented Programming in Visual Basic .NET
! Adding a property:
Public
Public Class
Class BankAccount
BankAccount
Private
Private customerName
customerName As
As String
String
Public
Public Property
Property Name(
Name( )) As
As String
String
Get
Get
Return
Return customerName
customerName
End Get
End Get
Set(ByVal
Set(ByVal Value
Value As
As String)
String)
customerName
customerName == Value
Value
End
End Set
Set
End
End Property
Property
End
End Class
Class
End Class
ReadOnly and WriteOnly Use the ReadOnly specifier in the property declaration to create only the Get
property. Use the WriteOnly specifier in the property declaration to create only
the Set property.
Module 7: Object-Oriented Programming in Visual Basic .NET 13
Module
Module Bank
Bank
Sub
Sub Main
Main
Dim
Dim account
account As
As New
New BankAccount(
BankAccount( ))
account.Deposit(500.00)
account.Deposit(500.00)
End
End Sub
Sub
End
End Module
Module
Example The following example shows how to create an instance of the BankAccount
class by using the New keyword:
Sub Main
Dim account As New BankAccount( )
account.Deposit(500.00)
End Sub
14 Module 7: Object-Oriented Programming in Visual Basic .NET
4. In the method, increment the value of the balance by adding amount to it, as
follows:
customerBalance += amount
End Property
8. Create a read-only property called Balance that returns the current balance,
as follows:
Public ReadOnly Property Balance( ) As Double
Get
Return customerBalance
End Get
End Property
16 Module 7: Object-Oriented Programming in Visual Basic .NET
The completed code for the BankAccount class should look like the following:
Public Class BankAccount
Private customerBalance As Double
Private customerName As String
4. Use the Name property to assign the name to the account, as follows:
account.Name = "Joe"
5. Use the Deposit method to deposit money into the account, as follows:
account.Deposit(500)
6. Use a message box to display the account name and balance, as follows:
MessageBox.Show ("Name: " & account.Name & _
". Balance: $" & account.Balance( ))
7. Change the startup object for the project to use Sub Main.
8. Build and run the program.
Module 7: Object-Oriented Programming in Visual Basic .NET 17
The completed code for the TestHarness module should look like the following
code:
Module TestHarness
account.Name = "Joe"
account.Deposit(500)
End Sub
End Module
Solution files The solution files for this practice are located in the install_folder\Practices\
Mod07\CreatingClass\Solution folder.
18 Module 7: Object-Oriented Programming in Visual Basic .NET
Public
Public Sub
Sub New(
New( ))
'' Perform
Perform simple
simple initialization
initialization
value =
value = 11
End
End Sub
Sub
Example of Sub New The following example shows how to use the Sub New constructor:
Public Sub New( )
' Perform simple initialization
intValue = 1
End Sub
The following line of code creates an object from a class named BankAccount,
which is already defined in the application.
Dim myAccount As New BankAccount( )
You can overload New and create as many class constructors as you require.
This is useful if you want to initialize your object when you create it.
Module 7: Object-Oriented Programming in Visual Basic .NET 19
Overloading You can overload constructors just as you can overload any other method in a
constructors class. However, you cannot use the Overloads keyword when overloading
constructors. The following example shows how to overload New and create
multiple class constructors:
Class BankAccount
Private balance as Double
Sub New( )
' Initialize balance
balance = 0.0
End Sub
One of the constructors in the above example takes a parameter. If you are
creating an object from such a class, you can include its parameters in the
declaration. The following example shows how to call the New method that
takes a parameter.
Dim myAccount As New BankAccount(120.00)
20 Module 7: Object-Oriented Programming in Visual Basic .NET
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
Note Visual Basic .NET allows for a second kind of destructor, named
Dispose, which can be explicitly called at any time to release resources
immediately. Dispose is beyond the scope of this course. For more information
about Dispose, see “Object Lifetime: How Objects Are Created and Destroyed”
in the Visual Studio .NET documentation.
Example of Sub Finalize The following example shows how to use the Finalize destructor:
Protected Overrides Sub Finalize( )
' Can close connections or other resources
conn.Close
End Sub
Lesson objectives After completing this lesson, you will be able to:
! Use shared data members to share data across class instances.
! Use shared methods.
22 Module 7: Object-Oriented Programming in Visual Basic .NET
Class
Class SavingsAccount
SavingsAccount
Public
Public Shared
Shared InterestRate
InterestRate As
As Double
Double
Public
Public Name As String, Balance As
Name As String, Balance As Double
Double
.. .. ..
End
End Class
Class
SavingsAccount.InterestRate
SavingsAccount.InterestRate == 0.03
0.03
Access levels Shared data members are directly linked to the class, and you can declare them
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 data members as private,
you provide public shared properties to access the private shared property.
Example The following example shows how to create a savings account class that uses a
public shared data member to maintain interest rates for a savings account:
Class SavingsAccount
Public Shared InterestRate As Double
The value of 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.
Module 7: Object-Oriented Programming in Visual Basic .NET 23
Calling shared data After you create a class that uses public shared data members, you can call the
members from a client data members of that class from a client application. The following code shows
how to call the SavingsAccount class and its data members from a client
application:
Sub Test( )
SavingsAccount.InterestRate = 0.03
MessageBox.Show(myAccount.CalculateInterest( ))
MessageBox.Show(yourAccount.CalculateInterest( ))
End Sub
Shared properties You can also create shared properties in your classes. The following example
shows how to declare a shared property called Rate in the SavingsAccount
class:
Class SavingsAccount
Private Shared interestRate As Double
Calling shared After you declare the shared property Rate, you can use it in a client application
properties from a client instead of directly accessing the shared data member interestRate. You can call
a shared property by qualifying it either with the class name or with the variable
name of a specific instance of the class.
The following code shows how to call a shared property by qualifying it with
the class name:
SavingsAccount.Rate = 0.03
The following code shows how to call a shared property by using the variable
name of a specific instance of the class:
myAccount.Rate = 0.04
24 Module 7: Object-Oriented Programming in Visual Basic .NET
'' TestClass
TestClass code
code
Public
Public Shared
Shared Function
Function GetComputerName(
GetComputerName( )) As
As String
String
...
...
End
End Function
Function
'' Client
Client code
code
MessageBox.Show(TestClass.GetComputerName(
MessageBox.Show(TestClass.GetComputerName( ))
))
Also note that, in the above code, Show is a shared method of the MessageBox
class.
Module 7: Object-Oriented Programming in Visual Basic .NET 25
End Function
End Function
26 Module 7: Object-Oriented Programming in Visual Basic .NET
Solution files The solution files for this practice are located in the install_folder\Practices\
Mod07\SharedMethod\Solution folder.
Module 7: Object-Oriented Programming in Visual Basic .NET 27
er itance
inh hism
m or p sses
p o ly c l a
r es and
tu
struc
e s p aces
nam
Lesson objectives After completing this lesson, you will be able to:
! Explain the concept of inheritance.
! Explain the concept of polymorphism.
! Compare classes to structures.
! Explain namespaces.
28 Module 7: Object-Oriented Programming in Visual Basic .NET
What Is Inheritance?
Note You can use the MyBase keyword to call methods in a base class when
you are overriding methods in a derived class. You can also use the MyBase
keyword to call the base class constructor and destructor in your derived class.
30 Module 7: Object-Oriented Programming in Visual Basic .NET
NotInheritable keyword You use the NotInheritable keyword to define a class that cannot be used as a
base class for inheritance. A compiler error is generated if another class
attempts to inherit from this class.
Example The following example shows how to use the NotInheritable keyword:
Public NotInheritable Class TestClass
...
End Class
Public Class DerivedClass
' The following line generates a compiler error
Inherits TestClass
...
End Class
MustInherit keyword You use the MustInherit keyword to define classes that are not intended to be
used directly as instantiated objects. The resulting class must be inherited as a
base class for use in an instantiated derived class object.
Example The following example shows how to use the MustInherit keyword:
Public MustInherit Class BaseClass
...
End Class
...
If the client code attempts to create an instance of this type of class, a compiler
error is generated, as shown in the following example:
' Client code
' The following line generates a compiler error
Dim x As New BaseClass( )
Protected keyword You use Protected access to limit the scope of a property, method, data
member, event, or event handler to the defining class and any derived class
based on that base class.
Example The following example shows how to use the Protected keyword:
Public Class BaseClass
' Accessible anywhere
Public counter As Integer
What Is Polymorphism?
BaseTax
BaseTax
CalculateTax(
CalculateTax( ))
CountyTax
CountyTax CityTax
CityTax
CalculateTax(
CalculateTax( )) CalculateTax(
CalculateTax( ))
Classes
Classes Structures
Structures
Can
Candefine
definedata
datamembers,
members, Can
Candefine
definedata
datamembers,
members,
properties,
properties, andmethods
and methods properties,
properties,and
andmethods
methods
Support
Supportconstructors
constructorsandand No
Nodefault
defaultconstructor
constructororor
member
memberinitialization
initialization member
memberinitialization
initialization
Support
SupportFinalize
Finalizemethod
method Do
Donot
notsupport
supportFinalize
Finalizemethod
method
Extensible
Extensibleby
byinheritance
inheritance Do
Donot
notsupport
supportinheritance
inheritance
Reference
Referencetype
type Value
Valuetype
type
Using a namespace At the project level, you must include a reference to the dynamic-link library
(DLL) that contains the namespace. In Visual Basic .NET, you use the Imports
statement to import the types contained in the given namespace so that they can
be referenced directly. The following code shows the use of the Imports
statement:
Imports System.Windows.Forms
If you omit the Imports statement, you will need to use the fully qualified
name of the namespace, as shown in the following example:
Public Class Form1
Inherits System.Windows.Forms.Form
Module 7: Object-Oriented Programming in Visual Basic .NET 35
Review
Write
! Understanding Classes
Create
Debug
Interface Code
and Deploy
! Working with Classes
Use Visual
Studio .NET
! Using Shared Members
! Inheritance,
Access Polymorphism, and
Data Debug
and Deploy
Namespaces
3. Write the code to create a public class called Student that has a private
instance data member named testScore of type Integer.
Public Class Student
Private testScore As Integer
End Class
36 Module 7: Object-Oriented Programming in Visual Basic .NET
4. Write code to add a read-only property called Score to the Student class.
Public Class Student
Private testScore As Integer
Public ReadOnly Property Score( ) As Integer
Get
Return testScore
End Get
End Property
End Class
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations.
Solution files The solution files for this lab are in the install_folder\Labfiles\
Lab071\Ex01\Solution folder.
Estimated time to
complete this lab:
30 minutes
38 Module 7: Object-Oriented Programming in Visual Basic .NET
Exercise 1
Creating a Derived Form Class
In this exercise, you will create a derived form class. This class will inherit
from the System.Windows.Forms class. You will add data members, a
method, and a constructor to create a simple form application that displays the
current date and time.
End Class
End Class
Module 7: Object-Oriented Programming in Visual Basic .NET 39
2. Create an instance of the Label type by using the New keyword. Your code
should look as follows:
Private Sub Initialize( )
Me.displayTimeLabel = New Label( )
End Sub
Your completed code for the Initialize method of the Clock class should
look like the following code:
Private Sub Initialize( )
Me.displayTimeLabel = New Label( )
Me.getTimeButton = New Button( )
Me.displayTimeLabel.BorderStyle = BorderStyle.Fixed3D
Me.displayTimeLabel.Left = 104
Me.displayTimeLabel.Top = 56
Me.displayTimeLabel.Height = 30
Me.displayTimeLabel.Width = 130
Me.Controls.Add(displayTimeLabel)
Me.getTimeButton.FlatStyle = FlatStyle.Flat
Me.getTimeButton.Left = 128
Me.getTimeButton.Top = 104
Me.getTimeButton.Text = "Date Time"
Me.Controls.Add(getTimeButton)
End Sub
End Sub
2. In the constructor, add a call to the base class constructor and the Initialize
method, as follows:
MyBase.New( )
Initialize( )
Module 7: Object-Oriented Programming in Visual Basic .NET 41