Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with.

Similar presentations


Presentation on theme: " 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with."— Presentation transcript:

1

2  2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with a Class 8.3 Class Scope 8.4 Controlling Access to Members 8.5 Initializing Class Objects: Constructors 8.6 Using Overloaded Constructors 8.7 Properties 8.8 Composition: Objects as Instance Variables of Other Classes 8.9 Using the Me Reference 8.10 Garbage Collection 8.11 Shared Class Members 8.12 Const and ReadOnly Members 8.13 Data Abstraction and Information Hiding 8.14 Software Reusability 8.15 Namespaces and Assemblies

3  2002 Prentice Hall. All rights reserved. 2 8.1 Introduction Object Orientation –Requires understanding of : Encapsulation: instance variable(data), methods (behaviors) Information hiding : implementation –Object Programming Class vs. user defined type Object instantiation vs. variable

4  2002 Prentice Hall. All rights reserved. 3 8.2 Implementing a Time Abstract Data type with a Class Abstract Data Types (ADT, i.e. Classes) –Instance variable Object in consistent state Initialize the instance variables Information hiding –Member access modifier Public: accessible whenever the program has a reference to the object Private: accessible only to methods of the class. Private methods are also called utility methods, or helper methods –Normally, instance variable are declared private, methods are declared public. However, it is OK to have private methods and public instance variables. –Predicate method: test the truth of a condition, like IsEmpty –Constructor: a special method to initialize an object’s instance variables, usually New

5  2002 Prentice Hall. All rights reserved. Outline 4 CTime.vb Class CTime inherits existing pieces of class Object. 1 ' Fig. 8.1: CTime.vb 2 ' Represents time in 24-hour format. 3 4 Class CTime 5 Inherits Object 6 7 ' declare Integer instance values for hour, minute and second 8 Private mHour As Integer ' 0 - 23 9 Private mMinute As Integer ' 0 - 59 10 Private mSecond As Integer ' 0 - 59 11 12 ' Method New is the CTime constructor method, which initializes 13 ' instance variables to zero 14 Public Sub New() 15 SetTime(0, 0, 0) 16 End Sub ' New 17 18 ' set new time value using universal time; 19 ' perform validity checks on data; 20 ' set invalid values to zero 21 Public Sub SetTime(ByVal hourValue As Integer, _ 22 ByVal minuteValue As Integer, ByVal secondValue As Integer) 23 24 ' check if hour is between 0 and 23, then set hour 25 If (hourValue >= 0 AndAlso hourValue < 24) Then 26 mHour = hourValue 27 Else 28 mHour = 0 29 End If 30 Introduces a New constructor and constructors do not return values CTime class definition Inherits Object indicates class CTime inherits existing pieces of class Object

6  2002 Prentice Hall. All rights reserved. Outline 5 CTime.vb 31 ' check if minute is between 0 and 59, then set minute 32 If (minuteValue >= 0 AndAlso minuteValue < 60) Then 33 mMinute = minuteValue 34 Else 35 mMinute = 0 36 End If 37 38 ' check if second is between 0 and 59, then set second 39 If (secondValue >= 0 AndAlso secondValue < 60) Then 40 mSecond = secondValue 41 Else 42 mSecond = 0 43 End If 44 45 End Sub ' SetTime 46 47 ' convert String to universal-time format 48 Public Function ToUniversalString() As String 49 Return String.Format("{0}:{1:D2}:{2:D2}", _ 50 mHour, mMinute, mSecond) 51 End Function ' ToUniversalString 52 53 ' convert to String in standard-time format 54 Public Function ToStandardString() As String 55 Dim suffix As String = " PM" 56 Dim format As String = "{0}:{1:D2}:{2:D2}" 57 Dim standardHour As Integer 58 59 ' determine whether time is AM or PM 60 If mHour < 12 Then 61 suffix = " AM" 62 End If 63 Argument 0 takes default format Arguments 1 and 2 take decimal number format Error checks input values for variables hourValue, minuteValue and secondValue

7  2002 Prentice Hall. All rights reserved. Outline 6 CTime.vb 64 ' convert from universal-time format to standard-time format 65 If (mHour = 12 OrElse mHour = 0) Then 66 standardHour = 12 67 Else 68 standardHour = mHour Mod 12 69 End If 70 71 Return String.Format(format, standardHour, mMinute, _ 72 mSecond) & suffix 73 End Function ' ToStandardString 74 75 End Class ' CTime Returns standard string from universal string

8  2002 Prentice Hall. All rights reserved. Outline 7 TimeTest.vb 1 ' Fig. 8.2: TimeTest.vb 2 ' Demonstrating class CTime. 3 4 Imports System.Windows.Forms 5 6 Module modTimeTest 7 8 Sub Main() 9 Dim time As New CTime() ' call CTime constructor 10 Dim output As String 11 12 output = "The initial universal times is: " & _ 13 time.ToUniversalString() & vbCrLf & _ 14 "The initial standard time is: " & _ 15 time.ToStandardString() 16 17 time.SetTime(13, 27, 6) ' set time with valid settings 18 19 output &= vbCrLf & vbCrLf & _ 20 "Universal time after setTime is: " & _ 21 time.ToUniversalString() & vbCrLf & _ 22 "Standard time after setTime is: " & _ 23 time.ToStandardString() 24 25 time.SetTime(99, 99, 99) ' set time with invalid settings 26 27 output &= vbCrLf & vbCrLf & _ 28 "After attempting invalid settings: " & vbCrLf & _ 29 "Universal time: " & time.ToUniversalString() & _ 30 vbCrLf & "Standard time: " & time.ToStandardString() 31 32 MessageBox.Show(output, "Testing Class CTime") 33 End Sub ' Main 34 35 End Module ' modTimeTest Invokes method setTime of class CTime and sets each Private instance variable to 0 Declares output as string Assigns time to output then converts To- UniveralString and ToStandardString Demonstrates both formats were set correctly Demonstrates that default values work correctly

9  2002 Prentice Hall. All rights reserved. Outline 8 TimeTest.vb

10  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 (ex., Public) can be accessed only through a “handle” (ObjectReferenceName.memberName) Variables within methods –Only methods can access that variable If a method defines a variable with the same name as an instance variable, the method-scope variable hides the class- scope variable in that method’s scope. Keyword Me –A hidden instance variable can be accessed in a method by preceding its name with the keyword Me and dot operator

11  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 for property Provide ability to access private data safely A Set accessor can provide data validation, and translate between the format of interface data and the format in the implementation A Get accessor can edit the data to limit the client’s view of that data

12  2002 Prentice Hall. All rights reserved. Outline 11 RestrictedAccess.vb 1 ' Fig. 8.3: RestrictedAccess.vb 2 ' Demonstrate error from attempt to access Private class member. 3 4 Module modRestrictedAccess 5 6 Sub Main() 7 Dim time As New CTime() 8 9 time.mHour = 7 ' error 10 End Sub ' Main 11 12 End Module ' modRestrictedAccess Cannot access a Private variable

13  2002 Prentice Hall. All rights reserved. 12 8.5 Initializing Class Objects: Constructors No return type Initializing Constructors –Invoked each time an object of the class is instantiated –If an instance variable is not initialized the compiler will assign a default value False for Booleans and Nothing for references –Classes can provide overloaded constructors (8.6) –Form of declarations Dim ObjectReference As New ClassName(arguments) Programs without default constructor are provided with one by the compiler, which contains no code and takes no argument

14  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 –VB runtime will invoke the appropriate constructor by matching the number, types, and order of argument

15  2002 Prentice Hall. All rights reserved. Outline 14 CTime2.vb 1 ' Fig. 8.4: CTime2.vb 2 ' Represents time and contains overloaded constructors. 3 4 Class CTime2 5 Inherits Object 6 7 ' declare Integers for hour, minute and second 8 Private mHour As Integer ' 0 - 23 9 Private mMinute As Integer ' 0 - 59 10 Private mSecond As Integer ' 0 - 59 11 12 ' constructor initializes each variable to zero and 13 ' ensures that each CTime2 object starts in consistent state 14 Public Sub New() 15 SetTime() 16 End Sub ' New 17 18 ' CTime2 constructor: hour supplied; 19 ' minute and second default to 0 20 Public Sub New(ByVal hourValue As Integer) 21 SetTime(hourValue) 22 End Sub ' New 23 24 ' CTime2 constructor: hour and minute supplied; 25 ' second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) 28 29 SetTime(hourValue, minuteValue) 30 End Sub ' New 31 32 ' CTime2 constructor: hour, minute and second supplied 33 Public Sub New(ByVal hourValue As Integer, _ 34 ByVal minuteValue As Integer, ByVal secondValue As Integer) 35 Initialize Private variables mHour, mMinute and mSecond to 0 Declares CTime2 constructor with one argument of hourValue Declares CTime2 constructor with two arguments of hourValue and minuteValue Declares CTime2 constructor with three arguments of hourValue, minuteValue secondValue

16  2002 Prentice Hall. All rights reserved. Outline 15 CTime2.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New 38 39 ' CTime2 constructor: another CTime2 object supplied 40 Public Sub New(ByVal timeValue As CTime2) 41 SetTime(timeValue.mHour, timeValue.mMinute, timeValue.mSecond) 42 End Sub ' New 43 44 ' set new time value using universal time; 45 ' perform validity checks on data; 46 ' set invalid values to zero 47 Public Sub SetTime(Optional ByVal hourValue As Integer = 0, _ 48 Optional ByVal minuteValue As Integer = 0, _ 49 Optional ByVal secondValue As Integer = 0) 50 51 ' perform validity checks on hour, then set hour 52 If (hourValue >= 0 AndAlso hourValue < 24) Then 53 mHour = hourValue 54 Else 55 mHour = 0 56 End If 57 58 ' perform validity checks on minute, then set minute 59 If (minuteValue >= 0 AndAlso minuteValue < 60) Then 60 mMinute = minuteValue 61 Else 62 mMinute = 0 63 End If 64 65 ' perform validity checks on second, then set second 66 If (secondValue >= 0 AndAlso secondValue < 60) Then 67 mSecond = secondValue 68 Else 69 mSecond = 0 70 End If Values of mHour, mMinute, and mSecond are initialized when supplied Error checks input values for variables hourValue, minuteValue, and secondValue

17  2002 Prentice Hall. All rights reserved. Outline 16 CTime2.vb 71 72 End Sub ' SetTime 73 74 ' convert String to universal-time format 75 Public Function ToUniversalString() As String 76 Return String.Format("{0}:{1:D2}:{2:D2}", _ 77 mHour, mMinute, mSecond) 78 End Function ' ToUniversalString 79 80 ' convert to String in standard-time format 81 Public Function ToStandardString() As String 82 Dim suffix As String = " PM" 83 Dim format As String = "{0}:{1:D2}:{2:D2}" 84 Dim standardHour As Integer 85 86 ' determine whether time is AM or PM 87 If mHour < 12 Then 88 suffix = " AM" 89 End If 90 91 ' convert from universal-time format to standard-time format 92 If (mHour = 12 OrElse mHour = 0) Then 93 standardHour = 12 94 Else 95 standardHour = mHour Mod 12 96 End If 97 98 Return String.Format(format, standardHour, mMinute, _ 99 mSecond) & suffix 100 End Function ' ToStandardString 101 102 End Class ' CTime2 0’s are placed for every missing values to satisfy SetTimes’s requirement

18  2002 Prentice Hall. All rights reserved. Outline 17 TimeTest2.vb 1 ' Fig. 8.5: TimeTest2.vb 2 ' Demonstrates overloading constructors. 3 4 Imports System.Windows.Forms 5 6 Module modTimeTest2 7 8 Sub Main() 9 10 ' use overloaded constructors 11 Dim time1 As New CTime2() 12 Dim time2 As New CTime2(2) 13 Dim time3 As New CTime2(21, 34) 14 Dim time4 As New CTime2(12, 25, 42) 15 Dim time5 As New CTime2(27, 74, 99) 16 Dim time6 As New CTime2(time4) ' use time4 as initial value 17 18 Const SPACING As Integer = 13 ' spacing between output text 19 20 ' invoke time1 methods 21 Dim output As String = "Constructed with: " & vbCrLf & _ 22 " time1: all arguments defaulted" & vbCrLf & _ 23 Space(SPACING) & time1.ToUniversalString() & _ 24 vbCrLf & Space(SPACING) & time1.ToStandardString() 25 26 ' invoke time2 methods 27 output &= vbCrLf & _ 28 " time2: hour specified; minute and second defaulted" & _ 29 vbCrLf & Space(SPACING) & _ 30 time2.ToUniversalString() & vbCrLf & Space(SPACING) & _ 31 time2.ToStandardString() 32 Time1 constructor has necessary number of arguments to be invoked Declares six different CTime objects that invoke various constructors of different class

19  2002 Prentice Hall. All rights reserved. Outline 18 TimeTest2.vb 33 ' invoke time3 methods 34 output &= vbCrLf & _ 35 " time3: hour and minute specified; second defaulted" & _ 36 vbCrLf & Space(SPACING) & time3.ToUniversalString() & _ 37 vbCrLf & Space(SPACING) & time3.ToStandardString() 38 39 ' invoke time4 methods 40 output &= vbCrLf & _ 41 " time4: hour, minute and second specified" & _ 42 vbCrLf & Space(SPACING) & time4.ToUniversalString() & _ 43 vbCrLf & Space(SPACING) & time4.ToStandardString() 44 45 ' invoke time5 methods 46 output &= vbCrLf & _ 47 " time5: hour, minute and second specified" & _ 48 vbCrLf & Space(SPACING) & time5.ToUniversalString() & _ 49 vbCrLf & Space(SPACING) & time5.ToStandardString() 50 51 ' invoke time6 methods 52 output &= vbCrLf & _ 53 " time6: Time2 object time4 specified" & vbCrLf & _ 54 Space(SPACING) & time6.ToUniversalString() & _ 55 vbCrLf & Space(SPACING) & time6.ToStandardString() 56 57 MessageBox.Show(output, _ 58 "Demonstrating Overloaded Constructor") 59 End Sub ' Main 60 61 End Module ' modTimeTest2 Shows the output in MessageBox.Show

20  2002 Prentice Hall. All rights reserved. Outline 19 TimeTest2.vb

21  2002 Prentice Hall. All rights reserved. 20 8.7 Properties Private and Public –Set accessor In Visual Basic instance variables as private does not guarantee data integrity. Validity checking must be done by programmers. Cannot return values indicating a failed attempt to assign invalid data to objects of the class. This could be done through exception handling (Ch 11). 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, and must be declared using keyword ReadOnly A property with only Set accessor is called WriteOnly, and must be declared using keyword WriteOnly. This is seldom used. – 訂正 : line 5 of p. 314, “or set (i.e. obtain value of)” should be “or get (i.e. obtain value of)”

22  2002 Prentice Hall. All rights reserved. Outline 21 CTime3.vb 1 ' Fig. 8.6: CTime3.vb 2 ' Represents time in 24-hour format and contains properties. 3 4 Class CTime3 5 Inherits Object 6 7 ' declare Integers for hour, minute and second 8 Private mHour As Integer 9 Private mMinute As Integer 10 Private mSecond As Integer 11 12 ' CTime3 constructor: initialize each instance variable to zero 13 ' and ensure that each CTime3 object starts in consistent state 14 Public Sub New() 15 SetTime(0, 0, 0) 16 End Sub ' New 17 18 ' CTime3 constructor: 19 ' hour supplied, minute and second defaulted to 0 20 Public Sub New(ByVal hourValue As Integer) 21 SetTime(hourValue, 0, 0) 22 End Sub ' New 23 24 ' CTime3 constructor: 25 ' hour and minute supplied; second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) 28 29 SetTime(hourValue, minuteValue, 0) 30 End Sub ' New 31 32 ' CTime3 constructor: hour, minute and second supplied 33 Public Sub New(ByVal hourValue As Integer, _ 34 ByVal minuteValue As Integer, ByVal secondValue As Integer) 35

23  2002 Prentice Hall. All rights reserved. Outline 22 CTime3.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New 38 39 ' CTime3 constructor: another CTime3 object supplied 40 Public Sub New(ByVal timeValue As CTime3) 41 SetTime(timeValue.mHour, timeValue.mMinute, _ 42 timeValue.mSecond) 43 End Sub ' New 44 45 ' set new time value using universal time; 46 ' uses properties to perform validity checks on data 47 Public Sub SetTime(ByVal hourValue As Integer, _ 48 ByVal minuteValue As Integer, ByVal secondValue As Integer) 49 50 Hour = hourValue ' looks 51 Minute = minuteValue ' dangerous 52 Second = secondValue ' but it is correct 53 End Sub ' SetTime 54 55 ' property Hour 56 Public Property Hour() As Integer 57 58 ' return mHour value 59 Get 60 Return mHour 61 End Get 62 63 ' set mHour value 64 Set(ByVal value As Integer) 65 66 If (value >= 0 AndAlso value < 24) Then 67 mHour = value 68 Else 69 mHour = 0 70 End If Defines the properties Hour of class CTime3 Error checks bogus input for variable mHour

24  2002 Prentice Hall. All rights reserved. Outline 23 CTime3.vb 71 72 End Set 73 74 End Property ' Hour 75 76 ' property Minute 77 Public Property Minute() As Integer 78 79 ' return mMinute value 80 Get 81 Return mMinute 82 End Get 83 84 ' set mMinute value 85 Set(ByVal value As Integer) 86 87 If (value >= 0 AndAlso value < 60) Then 88 mMinute = value 89 Else 90 mMinute = 0 91 End If 92 93 End Set 94 95 End Property ' Minute 96 97 ' property Second 98 Public Property Second() As Integer 99 100 ' return mSecond value 101 Get 102 Return mSecond 103 End Get 104 Defines the properties for Minute and error checks for erroneous input for variable value Sets variable mMinute to value

25  2002 Prentice Hall. All rights reserved. Outline 24 CTime3.vb 105 ' set mSecond value 106 Set(ByVal value As Integer) 107 108 If (value >= 0 AndAlso value < 60) Then 109 mSecond = value 110 Else 111 mSecond = 0 112 End If 113 114 End Set 115 116 End Property ' Second 117 118 ' convert String to universal-time format 119 Public Function ToUniversalString() As String 120 Return String.Format("{0}:{1:D2}:{2:D2}", _ 121 mHour, mMinute, mSecond) 122 End Function ' ToUniversalString 123 124 ' convert to String in standard-time format 125 Public Function ToStandardString() As String 126 Dim suffix As String = " PM" 127 Dim format As String = "{0}:{1:D2}:{2:D2}" 128 Dim standardHour As Integer 129 130 ' determine whether time is AM or PM 131 If mHour < 12 Then 132 suffix = " AM" 133 End If 134 Checks for erroneous input for variable value Sets variable mSecond to value

26  2002 Prentice Hall. All rights reserved. Outline 25 CTime3.vb 135 ' convert from universal-time format to standard-time format 136 If (mHour = 12 OrElse mHour = 0) Then 137 standardHour = 12 138 Else 139 standardHour = mHour Mod 12 140 End If 141 142 Return String.Format(format, standardHour, mMinute, _ 143 mSecond) & suffix 144 End Function ' ToStandardString 145 146 End Class ' CTime3

27  2002 Prentice Hall. All rights reserved. Outline 26 TimeTest3.vb 1 ' Fig. 8.7: TimeTest3.vb 2 ' Demonstrates Properties. 3 4 Imports System.Windows.Forms 5 6 Class FrmTimeTest3 7 Inherits Form 8 9 ' Label and TextBox for hour 10 Friend WithEvents lblSetHour As Label 11 Friend WithEvents txtSetHour As TextBox 12 13 ' Label and TextBox for minute 14 Friend WithEvents lblSetMinute As Label 15 Friend WithEvents txtSetMinute As TextBox 16 17 ' Label and TextBox for second 18 Friend WithEvents lblSetSecond As Label 19 Friend WithEvents txtSetSecond As TextBox 20 21 ' Labels for outputting time 22 Friend WithEvents lblOutput1 As Label 23 Friend WithEvents lblOutput2 As Label 24 25 ' Button for adding one second to time 26 Friend WithEvents cmdAddSecond As Button 27 28 Dim time As New CTime3() 29 30 ' Visual Studio.NET generated code 31

28  2002 Prentice Hall. All rights reserved. Outline 27 TimeTest3.vb 32 ' update time display 33 Private Sub UpdateDisplay() 34 lblOutput1.Text = "Hour: " & time.Hour & "; Minute: " & _ 35 time.Minute & "; Second: " & time.Second 36 37 lblOutput2.Text = "Standard time is: " & _ 38 time.ToStandardString & "; Universal Time is: " _ 39 & time.ToUniversalString() 40 End Sub ' UpdateDisplay 41 42 ' invoked when user presses Add Second button 43 Protected Sub cmdAddSecond_Click( _ 44 ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdAddSecond.Click 46 47 ' add one second 48 time.Second = (time.Second + 1) Mod 60 49 txtSetSecond.Text = time.Second 50 51 ' add one minute if 60 seconds have passed 52 If time.Second = 0 Then 53 time.Minute = (time.Minute + 1) Mod 60 54 txtSetMinute.Text = time.Minute 55 56 ' add one hour if 60 minutes have passed 57 If time.Minute = 0 Then 58 time.Hour = (time.Hour + 1) Mod 24 59 txtSetHour.Text = time.Hour 60 End If 61 62 End If 63 64 UpdateDisplay() 65 End Sub ' cmdAddSecond_Click 66 The method cmdAddSecond_Click determines and sets the new time

29  2002 Prentice Hall. All rights reserved. Outline 28 TimeTest3.vb 67 ' handle event when txtSetHour's text changes 68 Protected Sub txtSetHour_TextChanged(ByVal sender As _ 69 System.Object, ByVal e As System.EventArgs) _ 70 Handles txtSetHour.TextChanged 71 72 time.Hour = Convert.ToInt32(txtSetHour.Text) 73 UpdateDisplay() 74 End Sub ' txtSetHour_TextChanged 75 76 ' handle event when txtSetMinute's text changes 77 Protected Sub txtSetMinute_TextChanged(ByVal sender As _ 78 System.Object, ByVal e As System.EventArgs) _ 79 Handles txtSetMinute.TextChanged 80 81 time.Minute = Convert.ToInt32(txtSetMinute.Text) 82 UpdateDisplay() 83 End Sub ' txtSetMinute_TextChanged 84 85 ' handle event when txtSetSecond's text changes 86 Protected Sub txtSetSecond_TextChanged(ByVal sender _ 87 As System.Object, ByVal e As System.EventArgs) _ 88 Handles txtSetSecond.TextChanged 89 90 time.Second = Convert.ToInt32(txtSetSecond.Text) 91 UpdateDisplay() 92 End Sub ' txtSetSecond_TextChanged 93 94 End Class ' FrmTimeTest3 Declares three methods that use Hour, Minute and Second properties of CTime3 Object to alter time values

30  2002 Prentice Hall. All rights reserved. Outline 29 TimeTest3.vb

31  2002 Prentice Hall. All rights reserved. 30 8.8 Composition: Objects as Instance Variables of Other Classes The use of references to objects of preexisting classes as members of new objects is called composition. Referencing Existing Objects –Software Reuse: A form of composition is software reuse

32  2002 Prentice Hall. All rights reserved. Outline 31 CDay.vb 1 ' Fig. 8.8: CDay.vb 2 ' Encapsulates month, day and year. 3 4 Imports System.Windows.Forms 5 6 Class CDay 7 Inherits Object 8 9 Private mMonth As Integer ' 1-12 10 Private mDay As Integer ' 1-31 based on month 11 Private mYear As Integer ' any year 12 13 ' constructor confirms proper value for month, then calls 14 ' method CheckDay to confirm proper value for day 15 Public Sub New(ByVal monthValue As Integer, _ 16 ByVal dayValue As Integer, ByVal yearValue As Integer) 17 18 ' ensure month value is valid 19 If (monthValue > 0 AndAlso monthValue <= 12) Then 20 mMonth = monthValue 21 Else 22 mMonth = 1 23 24 ' inform user of error 25 Dim errorMessage As String = _ 26 "Month invalid. Set to month 1." 27 28 MessageBox.Show(errorMessage, "", _ 29 MessageBoxButtons.OK, MessageBoxIcon.Error) 30 End If 31 32 mYear = yearValue 33 mDay = CheckDay(dayValue) ' validate day 34 35 End Sub ' New Declares three integers mMonth, mDay, and mYear Constructor that receives three arguments Assigns values to class variables mMonth, mDay, mYear after error checking

33  2002 Prentice Hall. All rights reserved. Outline 32 CDay.vb 36 37 ' confirm proper day value based on month and year 38 Private Function CheckDay(ByVal testDayValue As Integer) _ 39 As Integer 40 41 Dim daysPerMonth() As Integer = _ 42 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 43 44 If (testDayValue > 0 AndAlso _ 45 testDayValue <= daysPerMonth(mMonth)) Then 46 47 Return testDayValue 48 End If 49 50 ' check for leap year in February 51 If (mMonth = 2 AndAlso testDayValue = 29 AndAlso _ 52 mYear Mod 400 = 0 OrElse mYear Mod 4 = 0 AndAlso _ 53 mYear Mod 100 <> 0) Then 54 55 Return testDayValue 56 Else 57 58 ' inform user of error 59 Dim errorMessage As String = _ 60 "day " & testDayValue & "invalid. Set to day 1. " 61 62 MessageBox.Show(errorMessage, "", _ 63 MessageBoxButtons.OK, MessageBoxIcon.Error) 64 65 Return 1 ' leave object in consistent state 66 End If 67 68 End Function ' CheckDay 69

34  2002 Prentice Hall. All rights reserved. Outline 33 CDay.vb 70 ' create string containing month/day/year format 71 Public Function ToStandardString() As String 72 Return mMonth & "/" & mDay & "/" & mYear 73 End Function ' ToStandardString 74 75 End Class ' CDay

35  2002 Prentice Hall. All rights reserved. Outline 34 CEmployee.vb 1 ' Fig. 8.9: CEmployee.vb 2 ' Represent employee name, birthday and hire date. 3 4 Class CEmployee 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 Private mBirthDate As CDay ' member object reference 10 Private mHireDate As CDay ' member object reference 11 12 ' CEmployee constructor 13 Public Sub New(ByVal firstNameValue As String, _ 14 ByVal lastNameValue As String, _ 15 ByVal birthMonthValue As Integer, _ 16 ByVal birthDayValue As Integer, _ 17 ByVal birthYearValue As Integer, _ 18 ByVal hireMonthValue As Integer, _ 19 ByVal hireDayValue As Integer, _ 20 ByVal hireYearValue As Integer) 21 22 mFirstName = firstNameValue 23 mLastName = lastNameValue 24 25 ' create CDay instance for employee birthday 26 mBirthDate = New CDay(birthMonthValue, birthDayValue, _ 27 birthYearValue) 28 29 ' create CDay instance for employee hire date 30 mHireDate = New CDay(hireMonthValue, hireDayValue, _ 31 hireYearValue) 32 End Sub ' New 33 Declares two Private strings and two Private object references Class CEmployee is composed of two references of class CDay, mBirthDate and mHireDate Arguments birthMonthValue, birthDayValue, and birthYearValue were passed to create mBirthDate object Arguments hireMonthValue, hireDayValue, and hireYearValue were passed to create mHireDate object

36  2002 Prentice Hall. All rights reserved. Outline 35 CEmployee.vb 34 ' return employee information as standard-format String 35 Public Function ToStandardString() As String 36 Return mLastName & ", " & mFirstName & " Hired: " _ 37 & mHireDate.ToStandardString() & " Birthday: " & _ 38 mBirthDate.ToStandardString() 39 End Function ' ToStandardString 40 41 End Class ' CEmployee

37  2002 Prentice Hall. All rights reserved. Outline 36 CompositionTest. vb 1 ' Fig. 8.10: CompositionTest.vb 2 ' Demonstrate an object with member object reference. 3 4 Imports System.Windows.Forms 5 6 Module modCompositionTest 7 8 Sub Main() 9 Dim employee As New CEmployee( _ 10 "Bob", "Jones", 7, 24, 1949, 3, 12, 1988) 11 12 MessageBox.Show(employee.ToStandardString(), _ 13 "Testing Class Employee") 14 End Sub ' Main 15 16 End Module ' modCompositionTest Instantiate a CEmployee object Outputs in MessageBox.Show

38  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

39  2002 Prentice Hall. All rights reserved. Outline 38 CTime4.vb 1 ' Fig. 8.11: CTime4.vb 2 ' Encapsulate time using Me reference. 3 4 Class CTime4 5 Private mHour, mMinute, mSecond As Integer 6 7 ' CTime4 constructor 8 Public Sub New(ByVal mHour As Integer, _ 9 ByVal mMinute As Integer, ByVal mSecond As Integer) 10 11 Me.mHour = mHour 12 Me.mMinute = mMinute 13 Me.mSecond = mSecond 14 End Sub ' New 15 16 ' create String using Me and implicit references 17 Public Function BuildString() As String 18 Return "Me.ToUniversalString(): " & Me.ToUniversalString() _ 19 & vbCrLf & "ToUniversalString(): " & ToUniversalString() 20 End Function ' BuildString 21 22 ' convert to String in standard-time format 23 Public Function ToUniversalString() As String 24 Return String.Format("{0:D2}:{1:D2}:{2:D2}", _ 25 mHour, mMinute, mSecond) 26 End Function ' ToUniversalString 27 28 End Class ' CTime4 The constructor receives three integer arguments to initialize a CTime4 object Reference Me can refer to any instance variable explicitly Uses reference Me explicitly Uses reference Me implicitly

40  2002 Prentice Hall. All rights reserved. Outline 39 MeTest.vb 1 ' Fig. 8.12: MeTest.vb 2 ' Demonstrates Me reference. 3 4 Imports System.Windows.Forms 5 6 Module modMeTest 7 8 Sub Main() 9 Dim time As New CTime4(12, 30, 19) 10 11 MessageBox.Show(time.BuildString(), _ 12 "Demonstrating the 'Me' Reference") 13 End Sub ' Main 14 15 End Module ' modMeTest Invokes method BuildString

41  2002 Prentice Hall. All rights reserved. 40 8.10 Garbage Collection Garbage collector –Resource leaks Objects must have an disciplined, efficient way to return memory and release resources when the program no longer uses those objects –Memory leaks: failure to return memory occupied –In Visual Basic memory is reclaimed automatically by locating objects with no references, hence it experiences rare memory leaks as compared to C and C++ –Some resources, like network connections, are better handled explicitly to be efficient Finalizer method performs termination housekeeping on that object just before the garbage collector reclaims the object's memory. Finalize method is defined in Object

42  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

43  2002 Prentice Hall. All rights reserved. Outline 42 CEmployee2.vb 1 ' Fig. 8.13: CEmployee2.vb 2 ' Class CEmployee2 uses Shared variable. 3 4 Class CEmployee2 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 10 ' number of objects in memory 11 Private Shared mCount As Integer 12 13 ' CEmployee2 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) 16 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New 25 26 ' finalizer method decrements Shared count of employees 27 Protected Overrides Sub Finalize() 28 mCount -= 1 ' decrement mCount, resulting in one fewer object 29 Console.WriteLine _ 30 ("Employee object finalizer: " & mFirstName & _ 31 " " & mLastName & "; count = " & mCount) 32 End Sub ' Finalize 33 Initializes mCount to 0 by default CEmployee2 constructor increments mCount Finalize method decrements mCount

44  2002 Prentice Hall. All rights reserved. Outline 43 CEmployee2.vb 34 ' return first name 35 Public ReadOnly Property FirstName() As String 36 37 Get 38 Return mFirstName 39 End Get 40 41 End Property ' FirstName 42 43 ' return last name 44 Public ReadOnly Property LastName() As String 45 46 Get 47 Return mLastName 48 End Get 49 50 End Property ' LastName 51 52 ' property Count 53 Public ReadOnly Shared Property Count() As Integer 54 55 Get 56 Return mCount 57 End Get 58 59 End Property ' Count 60 61 End Class ' CEmployee2 Member mCount can be referenced without declaring a CEmployee2 object

45  2002 Prentice Hall. All rights reserved. Outline 44 SharedTest.vb 1 ' Fig. 8.14: SharedTest.vb 2 ' Demonstrates Shared members. 3 4 Imports System.Windows.Forms 5 6 Module modSharedTest 7 8 Sub Main() 9 Dim output As String 10 11 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee2.Count) 13 14 Dim employee1 As CEmployee2 = _ 15 New CEmployee2("Susan", "Baker") 16 17 Dim employee2 As CEmployee2 = _ 18 New CEmployee2("Bob", "Jones") 19 20 ' output of employee2 after instantiation 21 Console.WriteLine(vbCrLf & _ 22 "Employees after instantiation: " & vbCrLf & _ 23 "via Employee.Count: " & CEmployee2.Count) 24 25 ' display name of first and second employee 26 Console.WriteLine(vbCrLf & "Employees 1: " & _ 27 employee1.FirstName & " " & employee1.LastName & _ 28 vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ 29 employee2.LastName) 30 31 ' mark employee1 and employee2 for garbage collection 32 employee1 = Nothing 33 employee2 = Nothing 34 Declares two CEmployee2 objects and increments mCount by two Sets objects’ references to Nothing

46  2002 Prentice Hall. All rights reserved. Outline 45 SharedTest.vb 35 System.GC.Collect() ' request garbage collection 36 End Sub ' Main 37 38 End Module ' modShared 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

47  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

48  2002 Prentice Hall. All rights reserved. Outline 47 CCircleConstants.vb 1 ' Fig. 8.15: CCircleConstants.vb 2 ' Encapsulate constants PI and radius. 3 4 Class CCircleConstants 5 6 ' PI is constant data member 7 Public Const PI As Double = 3.14159 8 9 ' radius is uninitialized constant 10 Public ReadOnly RADIUS As Integer 11 12 ' constructor of class CCircleConstants 13 Public Sub New(ByVal radiusValue As Integer) 14 RADIUS = radiusValue 15 End Sub ' New 16 17 End Class ' CCircleConstants Declares PI as a constant variable Declares RADIUS as a ReadOnly variable

49  2002 Prentice Hall. All rights reserved. Outline 48 ConstAndReadOnly.vb 1 ' Fig. 8.16: ConstAndReadOnly.vb 2 ' Demonstrates Const and ReadOnly members. 3 4 Imports System.Windows.Forms 5 6 Module modConstAndReadOnly 7 8 Sub Main() 9 Dim random As Random = New Random() 10 Dim circle As CCircleConstants = _ 11 New CCircleConstants(random.Next(1, 20)) 12 13 Dim radius As String = Convert.ToString(circle.RADIUS) 14 15 Dim output As String = "Radius = " & radius & vbCrLf _ 16 & "Circumference = " + String.Format("{0:N3}", _ 17 circle.RADIUS * 2 * CCircleConstants.PI) 18 19 MessageBox.Show(output, "Circumference", _ 20 MessageBoxButtons.OK, MessageBoxIcon.Information) 21 End Sub ' Main 22 23 End Module ' modConstAndReadOnly Generates a random number between 1-20 Access constant variable PI Access the ReadOnly variable RADIUS

50  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

51  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.

52  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

53  2002 Prentice Hall. All rights reserved. Outline 52 CEmployee3.vb 1 ' Fig. 8.17: CEmployee3.vb 2 ' Class CEmployee3 uses Shared variable. 3 4 Public Class CEmployee3 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 10 ' number of objects in memory 11 Private Shared mCount As Integer 12 13 ' CEmployee3 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) 16 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New 25 26 ' finalizer method decrements Shared count of employees 27 Protected Overrides Sub Finalize() 28 mCount -= 1 ' decrement mCount, resulting in one fewer object 29 Console.WriteLine _ 30 ("Employee object finalizer: " & mFirstName & _ 31 " " & mLastName & "; count = " & mCount) 32 End Sub ' Finalize 33 Declared as Public class CEmployee3

54  2002 Prentice Hall. All rights reserved. Outline 53 CEmployee3.vb 34 ' return first name 35 Public ReadOnly Property FirstName() As String 36 37 Get 38 Return mFirstName 39 End Get 40 41 End Property ' FirstName 42 43 ' return last name 44 Public ReadOnly Property LastName() As String 45 46 Get 47 Return mLastName 48 End Get 49 50 End Property ' LastName 51 52 ' property Count 53 Public ReadOnly Shared Property Count() As Integer 54 55 Get 56 Return mCount 57 End Get 58 59 End Property ' Count 60 61 End Class ' CEmployee3

55  2002 Prentice Hall. All rights reserved. 54 8.15 Namespaces and Assemblies Fig. 8.18Simple Class Library.

56  2002 Prentice Hall. All rights reserved. Outline 55 AssemblyTest.vb 1 ' Fig. 8.19: AssemblyTest.vb 2 ' Demonstrates assembly files and namespaces. 3 4 Imports EmployeeLibrary ' contains class CEmployee3 5 6 Module modAssemblyTest 7 8 Public Sub Main() 9 Dim output As String 10 11 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee3.Count) 13 14 Dim employee1 As CEmployee3 = _ 15 New CEmployee3("Susan", "Baker") 16 17 Dim employee2 As CEmployee3 = _ 18 New CEmployee3("Bob", "Jones") 19 20 ' output of employee after instantiation 21 Console.WriteLine(vbCrLf & "Employees after instantiation:" _ 22 & vbCrLf & "via Employee.Count: " & CEmployee3.Count) 23 24 ' display name of first and second employee 25 Console.WriteLine(vbCrLf & "Employees 1: " & _ 26 employee1.FirstName & " " & employee1.LastName & _ 27 vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ 28 employee2.LastName) 29 30 ' mark employee1 and employee2 for garbage collection 31 employee1 = Nothing 32 employee2 = Nothing 33 The module imports class CEmployee3

57  2002 Prentice Hall. All rights reserved. Outline 56 AssemblyTest.vb 34 System.GC.Collect() ' request garbage collection 35 End Sub ' Main 36 37 End Module ' modAssemblyTest 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

58  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

59  2002 Prentice Hall. All rights reserved. 58 8.16 Class View and Object Browser Fig. 8.20Class View of Fig. 8.1 and Fig. 8.2.

60  2002 Prentice Hall. All rights reserved. 59 8.16 Class View and Object Browser Fig. 8.21Object Browser when user selects Object from CTime.vb,

61  2002 Prentice Hall. All rights reserved. 60 8.16 Class View and Object Browser Fig. 8.21Object Browser when user selects Object from CTime.vb,


Download ppt " 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with."

Similar presentations


Ads by Google