Chapter08_PPT.ppt

Download Report

Transcript Chapter08_PPT.ppt

1
Chapter 8 – Object-Based Programming
Outline
8.1
8.2
8.3
8.4
8.5
8.6
8.7
8.8
8.9
8.10
8.11
8.12
8.13
8.14
8.15
Introduction
Implementing a Time Abstract Data Type with a Class
Class Scope
Controlling Access to Members
Initializing Class Objects: Constructors
Using Overloaded Constructors
Properties
Composition: Objects as Instance Variables of Other Classes
Using the Me Reference
Garbage Collection
Shared Class Members
Const and ReadOnly Members
Data Abstraction and Information Hiding
Software Reusability
Namespaces and Assemblies
 2002 Prentice Hall. All rights reserved.
2
8.1 Introduction
•
Object Orientation
– Requires understanding of:
•
•
Encapsulation
Information hiding
 2002 Prentice Hall. All rights reserved.
3
8.2 Implementing a Time Abstract Data type
with a Class
• Abstract Data Types (ADT)
– Instance variable
• Object in consistent state
• Initialize the instance variables
• Information hiding
 2002 Prentice Hall. All rights reserved.
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
' Fig. 8.1: CTime.vb
' Represents time in 24-hour format.
Class CTime
Inherits Object
CTime class definition
Class CTime inherits existing
pieces of class Object.
Outline
CTime.vb
' declare Integer instance values for hour, minute and second
Private mHour As Integer ' 0 - 23
Inherits 'Object
indicates class CTime
Private mMinute As Integer
0 - 59
Private mSecond As Integer
' 0 - 59pieces of class Object
inherits existing
' Method New is the CTime constructor method, which initializes
' instance variables to zeroIntroduces a New constructor
Public Sub New()
and constructors do not return
SetTime(0, 0, 0)
End Sub ' New
values
' set new time value using universal time;
' perform validity checks on data;
' set invalid values to zero
Public Sub SetTime(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As Integer)
' check if hour is between 0 and 23, then set hour
If (hourValue >= 0 AndAlso hourValue < 24) Then
mHour = hourValue
Else
mHour = 0
End If
 2002 Prentice Hall.
All rights reserved.
5
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
' check if minute is between 0 and 59, then set minute
If (minuteValue >= 0 AndAlso minuteValue < 60) Then
mMinute = minuteValue
Else
Error checks input values for variables
mMinute = 0
hourValue, minuteValue and
End If
Outline
CTime.vb
secondValue
' check if second is between 0 and 59, then set second
If (secondValue >= 0 AndAlso secondValue < 60) Then
mSecond = secondValue
Else
Argument 0 takes default value zero
mSecond = 0
Arguments 1 and 2 take decimal number
End If
format
End Sub ' SetTime
' convert String to universal-time format
Public Function ToUniversalString() As String
Return String.Format("{0}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
' convert to String in standard-time format
Public Function ToStandardString() As String
Dim suffix As String = " PM"
Dim format As String = "{0}:{1:D2}:{2:D2}"
Dim standardHour As Integer
' determine whether time is AM or PM
If mHour < 12 Then
suffix = " AM"
End If
 2002 Prentice Hall.
All rights reserved.
6
64
65
66
67
68
69
70
71
72
73
74
75
' convert from universal-time format to standard-time format
If (mHour = 12 OrElse mHour = 0) Then
standardHour = 12
Else
standardHour = mHour Mod 12
End If
Outline
CTime.vb
Return String.Format(format, standardHour, mMinute, _
mSecond) & suffix
End Function ' ToStandardString
End Class ' CTime
Returns standard string from
universal string
 2002 Prentice Hall.
All rights reserved.
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 8.2: TimeTest.vb
' Demonstrating class CTime.
Imports System.Windows.Forms
TimeTest.vb
Module modTimeTest
Sub Main()
Dim time As New CTime() ' call CTime constructor
Dim output As String
output = "The initial
universal
times
is: "of&class
_
Invokes
method
setTime
CTime
time.ToUniversalString() & vbCrLf & _
sets each Private instance variable to 0
"The initial standard time is: " & _
Declares output as string
time.ToStandardString()
and
time.SetTime(13, 27, 6) ' set time with valid settings
Assigns time to output then converts To-
output &= vbCrLf & vbCrLf & _
UniveralString
ToStandardString
"Universal
time and
after
setTime is: " & _
time.ToUniversalString() & vbCrLf & _
"Standard time after setTime is: " & _
time.ToStandardString()
time.SetTime(99, 99, 99) ' set time with invalid settings
Demonstrates both formats were set correctly
output &= vbCrLf & vbCrLf & _
"After attempting invalid settings: " & vbCrLf & _
"Universal time: " & time.ToUniversalString() & _
vbCrLf & "Standard time: " & time.ToStandardString()
MessageBox.Show(output, "Testing Class CTime")
End Sub ' Main
End Module ' modTimeTest
Demonstrates that default values work correctly
 2002 Prentice Hall.
All rights reserved.
8
Outline
TimeTest.vb
 2002 Prentice Hall.
All rights reserved.
9
8.3 Class Scope
• Class's Scope
– Instance variables and methods
• Class’s members
– Class members that are visible can be accessed only
through a “handle” (ObjectReferenceName.memberName)
• Variables within methods
– Only methods can access that variable
• Keyword Me
– A hidden instance variable can be accessed in a method by
preceding its name with the keyword Me and dot operator
 2002 Prentice Hall. All rights reserved.
10
8.4 Controlling Access to Members
• Public versus Private
– Control access to a class’s instance variables and methods
• Public
– Serve primarily to present interfaces of a class
• Private
– Holds clients private data safely
– Get and set functions
• Have ability to access private data
 2002 Prentice Hall. All rights reserved.
11
1
2
3
4
5
6
7
8
9
10
11
12
' Fig. 8.3: RestrictedAccess.vb
' Demonstrate error from attempt to access Private class member.
Module modRestrictedAccess
Sub Main()
Dim time As New CTime()
Cannot access a Private variable
Outline
RestrictedAccess
.vb
time.mHour = 7 ' error
End Sub ' Main
End Module ' modRestrictedAccess
 2002 Prentice Hall.
All rights reserved.
12
8.5 Initializing Class Objects: Constructors
• Initializing Constructors
– False for Booleans and Nothing for references
• If an instance variable is not initialized the compiler will assign
a default value
– Form of declarations
• Dim ObjectReference As New ClassName(arguments)
• Programs without default constructor are provided with one by
the compiler
 2002 Prentice Hall. All rights reserved.
13
8.6 Using Overloaded Constructors
• Overloaded Constructors
– Must have different numbers and/or types and/or orders of
parameters
 2002 Prentice Hall. All rights reserved.
14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 8.4: CTime2.vb
' Represents time and contains overloaded constructors.
Class CTime2
Inherits Object
Initialize Private vaiables mHour,
mMinute and mSecond to 0
' declare Integers for hour,
Private mHour As Integer
'
Private mMinute As Integer '
Private mSecond As Integer '
Outline
CTime2.vb
minute and second
0 - 23
0 - 59
0 - 59
' constructor initializes each variable to zero and
' ensures that each CTime2 object starts in consistent state
Public Sub New()
SetTime()
Declares CTime2 constructor with one
End Sub ' New
argument of hourValue
' CTime2 constructor: hour supplied;
' minute and second default to 0
Public Sub New(ByVal hourValue As Integer)
SetTime(hourValue)
End Sub ' New
Declares CTime2 constructor with
' CTime2 constructor: hour and minute supplied;
arguments
of hourValue,
minuteValue
'three
second
defaulted
to 0
Public
Sub New(ByVal hourValue As Integer, _
secondValue
ByVal minuteValue As Integer)
SetTime(hourValue, minuteValue)
Declares CTime2
End Sub ' New
constructor with two
arguments of hourValue and minuteValue
' CTime2 constructor: hour, minute and second supplied
Public Sub New(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As Integer)
 2002 Prentice Hall.
All rights reserved.
15
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Outline
SetTime(hourValue, minuteValue, secondValue)
End Sub ' New
' CTime2 constructor: another CTime2 object supplied
Public Sub New(ByVal timeValue As CTime2)
SetTime(timeValue.mHour, timeValue.mMinute, timeValue.mSecond)
End Sub ' New
CTime2.vb
' set new time value using universal time;
Valueson
of data;
mHour, mMinute, and mSecond are
' perform validity checks
' set invalid values initialized
to zero when supplied
Public Sub SetTime(Optional ByVal hourValue As Integer = 0, _
Optional ByVal minuteValue As Integer = 0, _
Optional ByVal secondValue As Integer = 0)
' perform validity checks on hour, then set hour
If (hourValue >= 0 AndAlso hourValue < 24) Then
mHour = hourValue
Else
mHour = 0
End If
' perform validity checks on minute, then set minute
If (minuteValue >= 0 AndAlso minuteValue < 60) Then
mMinute = minuteValue
Else
Error checks input values
mMinute = 0
variables hourValue,
End If
for
minuteValue, and secondValue
' perform validity checks on second, then set second
If (secondValue >= 0 AndAlso secondValue < 60) Then
mSecond = secondValue
Else
mSecond = 0
End If
 2002 Prentice Hall.
All rights reserved.
16
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Outline
End Sub ' SetTime
' convert String to universal-time format
Public Function ToUniversalString() As String
Return String.Format("{0}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
CTime2.vb
' convert to String in standard-time format
Public Function ToStandardString() As String
Dim suffix As String = " PM"
Dim format As String = "{0}:{1:D2}:{2:D2}"
Dim standardHour As Integer
0’s are placed for every
' determine whether time is AM or PM
missing values to satisfy
If mHour < 12 Then
suffix = " AM"
SetTimes’s requirement
End If
' convert from universal-time format to standard-time format
If (mHour = 12 OrElse mHour = 0) Then
standardHour = 12
Else
standardHour = mHour Mod 12
End If
Return String.Format(format, standardHour, mMinute, _
mSecond) & suffix
End Function ' ToStandardString
End Class ' CTime2
 2002 Prentice Hall.
All rights reserved.
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
' Fig. 8.5: TimeTest2.vb
' Demonstrates overloading constructors.
Imports System.Windows.Forms
Module modTimeTest2
Declares six different CTime objects that invoke
various constructors of different class
Outline
TimeTest2.vb
Sub Main()
' use overloaded
Dim time1 As New
Dim time2 As New
Dim time3 As New
Dim time4 As New
Dim time5 As New
Dim time6 As New
constructors
CTime2()
CTime2(2)
CTime2(21, 34)
CTime2(12, 25, 42)
CTime2(27, 74, 99)
CTime2(time4) ' use time4 as initial value
Const SPACING As Integer = 13 ' spacing between output text
' invoke time1 methods
Dim output As String = "Constructed with: " & vbCrLf & _
" time1: all arguments defaulted" & vbCrLf & _
Space(SPACING) & time1.ToUniversalString() & _
vbCrLf & Space(SPACING) & time1.ToStandardString()
' invoke time2 methods
Time1 constructor has necessary
output &= vbCrLf & _
" time2: hour specified;
minute
and second
number
of arguments
to defaulted"
be invoked & _
vbCrLf & Space(SPACING) & _
time2.ToUniversalString() & vbCrLf & Space(SPACING) & _
time2.ToStandardString()
 2002 Prentice Hall.
All rights reserved.
18
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
' invoke time3 methods
output &= vbCrLf & _
" time3: hour and minute specified; second defaulted" & _
vbCrLf & Space(SPACING) & time3.ToUniversalString() & _
vbCrLf & Space(SPACING) & time3.ToStandardString()
Outline
TimeTest2.vb
' invoke time4 methods
output &= vbCrLf & _
" time4: hour, minute and second specified" & _
vbCrLf & Space(SPACING) & time4.ToUniversalString() & _
vbCrLf & Space(SPACING) & time4.ToStandardString()
' invoke time5 methods
output &= vbCrLf & _
" time5: hour, minute and second specified" & _
vbCrLf & Space(SPACING) & time5.ToUniversalString() & _
vbCrLf & Space(SPACING) & time5.ToStandardString()
' invoke time6 methods
Shows the output in
output &= vbCrLf & _
" time6: Time2 object time4 specified"
& vbCrLf & _
MessageBox.Show
Space(SPACING) & time6.ToUniversalString() & _
vbCrLf & Space(SPACING) & time6.ToStandardString()
MessageBox.Show(output, _
"Demonstrating Overloaded Constructor")
End Sub ' Main
End Module ' modTimeTest2
 2002 Prentice Hall.
All rights reserved.
19
Outline
TimeTest2.vb
 2002 Prentice Hall.
All rights reserved.
20
8.7 Properties
• Private and Public
– Get accessor
• In Visual Basic instance variables as private does not guarantee
data integrity
– Set accessor
• Cannot return values indicating a failed attempt to assign
invalid data to objects of the class
• Control the setting of instance variables to valid values
– Get and Set accessors are not required
• A property with only Get accessor is called ReadOnly
• A property with only Set accessor is called WriteOnly
 2002 Prentice Hall. All rights reserved.
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 8.6: CTime3.vb
' Represents time in 24-hour format and contains properties.
Class CTime3
Inherits Object
Outline
CTime3.vb
' declare Integers for hour, minute and second
Private mHour As Integer
Private mMinute As Integer
Private mSecond As Integer
' CTime3 constructor: initialize each instance variable to zero
' and ensure that each CTime3 object starts in consistent state
Public Sub New()
SetTime(0, 0, 0)
End Sub ' New
' CTime3 constructor:
' hour supplied, minute and second defaulted to 0
Public Sub New(ByVal hourValue As Integer)
SetTime(hourValue, 0, 0)
End Sub ' New
' CTime3 constructor:
' hour and minute supplied; second defaulted to 0
Public Sub New(ByVal hourValue As Integer, _
ByVal minuteValue As Integer)
SetTime(hourValue, minuteValue, 0)
End Sub ' New
' CTime3 constructor: hour, minute and second supplied
Public Sub New(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As Integer)
 2002 Prentice Hall.
All rights reserved.
22
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
SetTime(hourValue, minuteValue, secondValue)
End Sub ' New
' CTime3 constructor: another CTime3 object supplied
Public Sub New(ByVal timeValue As CTime3)
SetTime(timeValue.mHour, timeValue.mMinute, _
timeValue.mSecond)
End Sub ' New
Outline
CTime3.vb
' set new time value using universal time;
' uses properties to perform validity checks on data
Public Sub SetTime(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As Integer)
Hour =
Minute
Second
End Sub '
hourValue
' looks
= minuteValue ' dangerous
= secondValue ' but it is correct
SetTime
' property Hour
Public Property Hour() As Integer
' return mHour value
Get
Return mHour
End Get
' set mHour value
Set(ByVal value As Integer)
Defines the properties
Hour of class CTime3
Error checks bogus input
for variable mHour
If (value >= 0 AndAlso value < 24) Then
mHour = value
Else
mHour = 0
End If
 2002 Prentice Hall.
All rights reserved.
23
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Outline
End Set
End Property ' Hour
CTime3.vb
' property Minute
Public Property Minute() As Integer
' return mMinute value
Get
Return mMinute
End Get
' set mMinute value
Set(ByVal value As Integer)
If (value >= 0 AndAlso value < 60) Then
mMinute = value
Else
mMinute = 0
Defines the properties for Minute
End If
End Set
and error
checks for erroneous input for variable value
Sets variable mMinute to value
End Property ' Minute
' property Second
Public Property Second() As Integer
' return mSecond value
Get
Return mSecond
End Get
 2002 Prentice Hall.
All rights reserved.
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
' set mSecond value
Set(ByVal value As Integer)
If (value >= 0 AndAlso value < 60) Then
mSecond = value
Else
mSecond = 0
End If
End Set
End Property ' Second
24
Outline
CTime3.vb
Checks for erroneous input for variable value
Sets variable mSecond to value
' convert String to universal-time format
Public Function ToUniversalString() As String
Return String.Format("{0}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
' convert to String in standard-time format
Public Function ToStandardString() As String
Dim suffix As String = " PM"
Dim format As String = "{0}:{1:D2}:{2:D2}"
Dim standardHour As Integer
' determine whether time is AM or PM
If mHour < 12 Then
suffix = " AM"
End If
 2002 Prentice Hall.
All rights reserved.
25
135
136
137
138
139
140
141
142
143
144
145
146
' convert from universal-time format to standard-time format
If (mHour = 12 OrElse mHour = 0) Then
standardHour = 12
Else
standardHour = mHour Mod 12
End If
Outline
CTime3.vb
Return String.Format(format, standardHour, mMinute, _
mSecond) & suffix
End Function ' ToStandardString
End Class
' CTime3
 2002 Prentice Hall.
All rights reserved.
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
' Fig. 8.7: TimeTest3.vb
' Demonstrates Properties.
Imports System.Windows.Forms
Outline
TimeTest3.vb
Class FrmTimeTest3
Inherits Form
' Label and TextBox for hour
Friend WithEvents lblSetHour As Label
Friend WithEvents txtSetHour As TextBox
' Label and TextBox for minute
Friend WithEvents lblSetMinute As Label
Friend WithEvents txtSetMinute As TextBox
' Label and TextBox for second
Friend WithEvents lblSetSecond As Label
Friend WithEvents txtSetSecond As TextBox
' Labels for outputting time
Friend WithEvents lblOutput1 As Label
Friend WithEvents lblOutput2 As Label
' Button for adding one second to time
Friend WithEvents cmdAddSecond As Button
Dim time As New CTime3()
' Visual Studio .NET generated code
 2002 Prentice Hall.
All rights reserved.
27
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
' update time display
Private Sub UpdateDisplay()
lblOutput1.Text = "Hour: " & time.Hour & "; Minute: " & _
time.Minute & "; Second: " & time.Second
Outline
TimeTest3.vb
lblOutput2.Text = "Standard time is: " & _
time.ToStandardString & "; Universal Time is: " _
& time.ToUniversalString()
End Sub ' UpdateDisplay
' invoked when user presses Add Second button
Protected Sub cmdAddSecond_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdAddSecond.Click
' add one second
time.Second = (time.Second + 1) Mod 60
txtSetSecond.Text = time.Second
' add one minute if 60 seconds have passed
If time.Second = 0 Then
time.Minute = (time.Minute + 1) Mod 60
The method cmdAddSecond_Click
txtSetMinute.Text = time.Minute
determines and sets the new time
' add one hour if 60 minutes have passed
If time.Minute = 0 Then
time.Hour = (time.Hour + 1) Mod 24
txtSetHour.Text = time.Hour
End If
End If
UpdateDisplay()
End Sub ' cmdAddSecond_Click
 2002 Prentice Hall.
All rights reserved.
28
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
' handle event when txtSetHour's text changes
Protected Sub txtSetHour_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles txtSetHour.TextChanged
Outline
TimeTest3.vb
time.Hour = Convert.ToInt32(txtSetHour.Text)
UpdateDisplay()
End Sub ' txtSetHour_TextChanged
three methodstext
that use
Hour, Minute and
' handle event Declares
when txtSetMinute's
changes
Protected Sub txtSetMinute_TextChanged(ByVal
sender
As time
_
Second properties of CTime3 Object
to alter
values
System.Object, ByVal e As System.EventArgs) _
Handles txtSetMinute.TextChanged
time.Minute = Convert.ToInt32(txtSetMinute.Text)
UpdateDisplay()
End Sub ' txtSetMinute_TextChanged
' handle event when txtSetSecond's text changes
Protected Sub txtSetSecond_TextChanged(ByVal sender _
As System.Object, ByVal e As System.EventArgs) _
Handles txtSetSecond.TextChanged
time.Second = Convert.ToInt32(txtSetSecond.Text)
UpdateDisplay()
End Sub ' txtSetSecond_TextChanged
End Class ' FrmTimeTest3
 2002 Prentice Hall.
All rights reserved.
29
Outline
TimeTest3.vb
 2002 Prentice Hall.
All rights reserved.
30
8.8 Composition: Objects as Instance
Variables of Other Classes
• Referencing Existing Objects
– Software Reuse:
• A form of composition is software reuse
 2002 Prentice Hall. All rights reserved.
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 8.8: CDay.vb
' Encapsulates month, day and year.
Imports System.Windows.Forms
Class CDay
Inherits Object
Declares three integers
mMonth, mDay, and mYear
CDay.vb
Private mMonth As Integer ' 1-12
Private mDay As Integer ' 1-31 based on month
Private mYear As Integer ' any year
' constructor confirms proper value for month, then calls
' method CheckDay to confirm proper value for day
Public Sub New(ByVal monthValue As Integer, _
ByVal dayValue As Integer, ByVal yearValue As Integer)
' ensure month value is valid
If (monthValue > 0 AndAlso monthValue <= 12) Then
mMonth = monthValue
Constructor that receives three
Else
mMonth = 1
arguments
' inform user of error
Dim errorMessage As String = _
Assigns values to class
"Month invalid. Set to month 1."
variables mMonth,
mDay, mYear after error checking
MessageBox.Show(errorMessage, "", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
mYear = yearValue
mDay = CheckDay(dayValue) ' validate day
End Sub ' New
 2002 Prentice Hall.
All rights reserved.
32
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
' confirm proper day value based on month and year
Private Function CheckDay(ByVal testDayValue As Integer) _
As Integer
Outline
CDay.vb
Dim daysPerMonth() As Integer = _
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
If (testDayValue > 0 AndAlso _
testDayValue <= daysPerMonth(mMonth)) Then
Return testDayValue
End If
' check for leap year in February
If (mMonth = 2 AndAlso testDayValue = 29 AndAlso _
mYear Mod 400 = 0 OrElse mYear Mod 4 = 0 AndAlso _
mYear Mod 100 <> 0) Then
Return testDayValue
Else
' inform user of error
Dim errorMessage As String = _
"day " & testDayValue & "invalid. Set to day 1. "
MessageBox.Show(errorMessage, "", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return 1 ' leave object in consistent state
End If
End Function ' CheckDay
 2002 Prentice Hall.
All rights reserved.
33
70
71
72
73
74
75
' create string containing month/day/year format
Public Function ToStandardString() As String
Return mMonth & "/" & mDay & "/" & mYear
End Function ' ToStandardString
Outline
CDay.vb
End Class ' CDay
 2002 Prentice Hall.
All rights reserved.
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
' Fig. 8.9: CEmployee.vb
' Represent employee name, birthday and hire date.
Class CEmployee
Inherits Object
Private
Private
Private
Private
Declares two Private strings and
two Private object references
Outline
CEmployee.vb
mFirstName As String
mLastName As String
mBirthDate As CDay ' member object reference
mHireDate As CDay ' member object reference
' CEmployee constructorClass CEmployee is composed of two references
Public Sub New(ByVal firstNameValue As String, _
of class CDay, mBirthDate and mHireDate
ByVal lastNameValue As String, _
ByVal birthMonthValue As Integer, _
ByVal birthDayValue As Integer, _
ByVal birthYearValue
As Integer, _
Arguments birthMonthValue,
birthDayValue, and
ByVal hireMonthValue As Integer, _
birthYearValue were passed to create mBirthDate object
ByVal hireDayValue As Integer, _
ByVal hireYearValue As Integer)
mFirstName = firstNameValue
mLastName = lastNameValue
Arguments hireMonthValue, hireDayValue, and
CDayhireYearValue
instance for were
employee
passedbirthday
to create mHireDate object
' create
mBirthDate = New CDay(birthMonthValue, birthDayValue, _
birthYearValue)
' create CDay instance for employee hire date
mHireDate = New CDay(hireMonthValue, hireDayValue, _
hireYearValue)
End Sub ' New
 2002 Prentice Hall.
All rights reserved.
35
34
35
36
37
38
39
40
41
' return employee information as standard-format String
Public Function ToStandardString() As String
Return mLastName & ", " & mFirstName & " Hired: " _
& mHireDate.ToStandardString() & " Birthday: " & _
mBirthDate.ToStandardString()
End Function ' ToStandardString
Outline
CEmployee.vb
End Class ' CEmployee
 2002 Prentice Hall.
All rights reserved.
36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
' Fig. 8.10: CompositionTest.vb
' Demonstrate an object with member object reference.
Imports System.Windows.Forms
Module modCompositionTest
Instantiate a CEmployee object
Outputs in MessageBox.Show
Outline
CompositionTest.
vb
Sub Main()
Dim employee As New CEmployee( _
"Bob", "Jones", 7, 24, 1949, 3, 12, 1988)
MessageBox.Show(employee.ToStandardString(), _
"Testing Class Employee")
End Sub ' Main
End Module ' modCompositionTest
 2002 Prentice Hall.
All rights reserved.
37
8.9 Using the Me Reference
• Me Reference
– Every object can access a reference to itself using a Me
reference.
• Me explicitly
• Me implicitly
– The explicit use of the Me reference can increase program
clarity where Me is optional
 2002 Prentice Hall. All rights reserved.
38
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
' Fig. 8.11: CTime4.vb
' Encapsulate time using Me reference.
Class CTime4
The constructor
Private mHour, mMinute, mSecond As Integer
receives three integer
arguments to initialize a CTime4 object
Outline
CTime4.vb
' CTime4 constructor
Public Sub New(ByVal mHour As Integer, _
ByVal mMinute As Integer, ByVal mSecond As Integer)
Me.mHour = mHour
Me.mMinute = mMinute
Me.mSecond
= mSecond
Uses reference
Me explicitly
End Sub ' New
Reference Me can refer to
any instance variable explicitly
' create String using Me and implicit references
Public Function BuildString() As String
Return "Me.ToUniversalString(): " & Me.ToUniversalString() _
& vbCrLf & "ToUniversalString(): " & ToUniversalString()
End Function ' BuildString
' convertMe
to implicitly
String in
Uses reference
standard-time format
Public Function ToUniversalString() As String
Return String.Format("{0:D2}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
End Class ' CTime4
 2002 Prentice Hall.
All rights reserved.
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Outline
' Fig. 8.12: MeTest.vb
' Demonstrates Me reference.
Imports System.Windows.Forms
Invokes method BuildString
MeTest.vb
Module modMeTest
Sub Main()
Dim time As New CTime4(12, 30, 19)
MessageBox.Show(time.BuildString(), _
"Demonstrating the 'Me' Reference")
End Sub ' Main
End Module ' modMeTest
 2002 Prentice Hall.
All rights reserved.
40
8.10 Garbage Collection
• Garbage collector
– Resource leaks
• Objects must have an efficient way to return memory and
release resources when the program no longer uses those
objects
– Memory leaks
• In Visual Basic memory is reclaimed automatically, hence it
experiences rare memory leaks as compared to C and C++
– Finalization
• Finalizer method performs termination housekeeping on that
object just before the garbage collector reclaims the object's
memory.
 2002 Prentice Hall. All rights reserved.
41
8.11 Shared Class Members
• Shared Class Variable
– Contains only one copy of this variable in memory
• When a single copy of the data will suffice, use Shared class
variables to save storage.
• Shared class variables are not the same as global variables
because Shared class variables have class scope
• Shared method has no Me reference
 2002 Prentice Hall. All rights reserved.
42
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
' Fig. 8.13: CEmployee2.vb
' Class CEmployee2 uses Shared variable.
Class CEmployee2
Inherits Object
Outline
CEmployee2.vb
Private mFirstName As String
Private mLastName As String
Initializes mCount to 0 by default
' number of objects in memory
Private Shared mCount As Integer
' CEmployee2 constructor
Public Sub New(ByVal firstNameValue As String, _
ByVal lastNameValue As String)
mFirstName = firstNameValue
mLastName = lastNameValue
mCount += 1 ' increment shared count of employees
Console.WriteLine _
("Employee object constructor: " & mFirstName & _
" " & mLastName)
CEmployee2 constructor increments mCount
End Sub ' New
Finalize method decrements mCount
' finalizer method decrements Shared count of employees
Protected Overrides Sub Finalize()
mCount -= 1 ' decrement mCount, resulting in one fewer object
Console.WriteLine _
("Employee object finalizer: " & mFirstName & _
" " & mLastName & "; count = " & mCount)
End Sub ' Finalize
 2002 Prentice Hall.
All rights reserved.
43
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
' return first name
Public ReadOnly Property FirstName() As String
Get
Outline
CEmployee2.vb
Return mFirstName
End Get
End Property ' FirstName
' return last name
Public ReadOnly Property LastName() As String
Get
Return mLastName
End Get
Member mCount can be referenced without
declaring a CEmployee2 object
End Property ' LastName
' property Count
Public ReadOnly Shared Property Count() As Integer
Get
Return mCount
End Get
End Property ' Count
End Class ' CEmployee2
 2002 Prentice Hall.
All rights reserved.
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
' Fig. 8.14: SharedTest.vb
' Demonstrates Shared members.
Imports System.Windows.Forms
SharedTest.vb
Module modSharedTest
Sub Main()
Dim output As String
Declares two CEmployee2 objects
Console.WriteLine("Employees before instantiation: " & _
and increments mCount by two
CEmployee2.Count)
Dim employee1 As CEmployee2 = _
New CEmployee2("Susan", "Baker")
Dim employee2 As CEmployee2 = _
New CEmployee2("Bob", "Jones")
' output of employee2 after instantiation
Console.WriteLine(vbCrLf & _
"Employees after instantiation: " & vbCrLf & _
"via Employee.Count: " & CEmployee2.Count)
' display name of first and second employee
Console.WriteLine(vbCrLf & "Employees 1: " & _
employee1.FirstName & " " & employee1.LastName & _
vbCrLf & "Employee 2: " & employee2.FirstName & " " & _
employee2.LastName)
Sets objects’ references to Nothing
' mark employee1 and employee2 for garbage collection
employee1 = Nothing
employee2 = Nothing
 2002 Prentice Hall.
All rights reserved.
45
35
36
37
38
System.GC.Collect() ' request garbage collection
End Sub ' Main
End Module ' modShared
Outline
SharedTest.vb
Employees before instantiation: 0
Employee object constructor: Susan Baker
Employee object constructor: Bob Jones
Employees after instantiation:
via Employee.Count: 2
Employees 1: Susan Baker
Employee 2: Bob Jones
Employee object finalizer: Bob Jones; count = 1
Employee object finalizer: Susan Baker; count = 0
 2002 Prentice Hall.
All rights reserved.
46
8.12 Const and ReadOnly Members
• Const or ReadOnly
– Const
• A data member must be initialized in its declaration
• Cannot be modified once initialized
– ReadOnly
• A data member can be initialized either in the class structure or
in its declaration
• Cannot be modified once initialized
 2002 Prentice Hall. All rights reserved.
47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
' Fig. 8.15: CCircleConstants.vb
' Encapsulate constants PI and radius.
Class CCircleConstants
Declares PI as a constant variable
' PI is constant data member
Public Const PI As Double = 3.14159
Outline
CCircleConstants
.vb
' radius is uninitialized constant
Public ReadOnly RADIUS As Integer
' constructor of class CCircleConstants
Public Sub New(ByVal radiusValue As Integer)
RADIUS = radiusValue
End Sub ' New
Declares RADIUS as a ReadOnly variable
End Class ' CCircleConstants
 2002 Prentice Hall.
All rights reserved.
48
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
' Fig. 8.16: ConstAndReadOnly.vb
' Demonstrates Const and ReadOnly members.
Imports System.Windows.Forms
Generates a random number between 1-20
Module modConstAndReadOnly
Outline
ConstAndReadOnly
.vb
Access
ReadOnly variable RADIUS
Sub the
Main()
Dim random As Random = New Random()
Dim circle As CCircleConstants = _
New CCircleConstants(random.Next(1, 20))
Dim radius As String = Convert.ToString(circle.RADIUS)
Dim output As String = "Radius = " & radius & vbCrLf _
& "Circumference = " + String.Format("{0:N3}", _
circle.RADIUS * 2 * CCircleConstants.PI)
MessageBox.Show(output, "Circumference", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Access constant variable PI
End Sub ' Main
End Module ' modConstAndReadOnly
 2002 Prentice Hall.
All rights reserved.
49
8.13 Data Abstraction and Information
Hiding
• Stacks
– Last-in, first out (LIFO)
• Cafeteria trays that are put on top of each other
• Stacks offer functions such as push and pop
• Queue
– First-In, first-out (FIFO)
• Printing machine that prints documents in FIFO order
• Queue offer functions such as enqueue and dequeue
 2002 Prentice Hall. All rights reserved.
50
8.14 Software Reusability
• Rapid application development (RAD)
– Software reusability
• Software reusability speeds the development of powerful, high
quality software.
 2002 Prentice Hall. All rights reserved.
51
8.15 Namespaces and Assemblies
• Framework Class Library
– .NET Framework:
• Must be imported to a Visual Basic program by including a
reference to those libraries
– Namespaces:
• Namespaces help minimize naming collisions by proving a
convention for unique class names
 2002 Prentice Hall. All rights reserved.
52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
' Fig. 8.17: CEmployee3.vb
' Class CEmployee3 uses Shared variable.
Public Class CEmployee3
Inherits Object
Private mFirstName As String
Private mLastName As String
Outline
CEmployee3.vb
Declared as Public class CEmployee3
' number of objects in memory
Private Shared mCount As Integer
' CEmployee3 constructor
Public Sub New(ByVal firstNameValue As String, _
ByVal lastNameValue As String)
mFirstName = firstNameValue
mLastName = lastNameValue
mCount += 1 ' increment shared count of employees
Console.WriteLine _
("Employee object constructor: " & mFirstName & _
" " & mLastName)
End Sub ' New
' finalizer method decrements Shared count of employees
Protected Overrides Sub Finalize()
mCount -= 1 ' decrement mCount, resulting in one fewer object
Console.WriteLine _
("Employee object finalizer: " & mFirstName & _
" " & mLastName & "; count = " & mCount)
End Sub ' Finalize
 2002 Prentice Hall.
All rights reserved.
53
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
' return first name
Public ReadOnly Property FirstName() As String
Get
Return mFirstName
End Get
Outline
CEmployee3.vb
End Property ' FirstName
' return last name
Public ReadOnly Property LastName() As String
Get
Return mLastName
End Get
End Property ' LastName
' property Count
Public ReadOnly Shared Property Count() As Integer
Get
Return mCount
End Get
End Property ' Count
End Class ' CEmployee3
 2002 Prentice Hall.
All rights reserved.
54
8.15 Namespaces and Assemblies
Fig. 8.18 Simple Class Library.
 2002 Prentice Hall. All rights reserved.
55
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
' Fig. 8.19: AssemblyTest.vb
' Demonstrates assembly files and namespaces.
Imports EmployeeLibrary ' contains class CEmployee3
Outline
AssemblyTest.vb
Module modAssemblyTest
Public Sub Main() The module
Dim output As String
imports class CEmployee3
Console.WriteLine("Employees before instantiation: " & _
CEmployee3.Count)
Dim employee1 As CEmployee3 = _
New CEmployee3("Susan", "Baker")
Dim employee2 As CEmployee3 = _
New CEmployee3("Bob", "Jones")
' output of employee after instantiation
Console.WriteLine(vbCrLf & "Employees after instantiation:" _
& vbCrLf & "via Employee.Count: " & CEmployee3.Count)
' display name of first and second employee
Console.WriteLine(vbCrLf & "Employees 1: " & _
employee1.FirstName & " " & employee1.LastName & _
vbCrLf & "Employee 2: " & employee2.FirstName & " " & _
employee2.LastName)
' mark employee1 and employee2 for garbage collection
employee1 = Nothing
employee2 = Nothing
 2002 Prentice Hall.
All rights reserved.
56
34
35
36
37
System.GC.Collect() ' request garbage collection
End Sub ' Main
End Module ' modAssemblyTest
Outline
AssemblyTest.vb
Employees before instantiation: 0
Employee object constructor: Susan Baker
Employee object constructor: Bob Jones
Employees after instantiation:
via Employee.Count: 2
Employees 1: Susan Baker
Employee 2: Bob Jones
Employee object finalizer: Bob Jones; count = 1
Employee object finalizer: Susan Baker; count = 0
 2002 Prentice Hall.
All rights reserved.
57
8.16 Class View and Object Browser
• Class View
– Displays a project’s class members
• To access this feature select VIEW>CLASS VIEW
• (+) node called collapsed
• (-) node is called expanded
• Object Browser
– Lists the Framework Class Library Available in Visual Basic
• To access this feature, right click any Visual Basic class or
method in the code editor and select Go To Definition
• It illustrates the functionally provided by a specific object
 2002 Prentice Hall. All rights reserved.
58
8.16 Class View and Object Browser
Fig. 8.20 Class View of Fig. 8.1 and Fig. 8.2.
 2002 Prentice Hall. All rights reserved.
59
8.16 Class View and Object Browser
Fig. 8.21 Object Browser when user selects Object from CTime.vb,
 2002 Prentice Hall. All rights reserved.
60
8.16 Class View and Object Browser
Fig. 8.21 Object Browser when user selects Object from CTime.vb,
 2002 Prentice Hall. All rights reserved.