Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 – Object-Based Programming

Similar presentations


Presentation on theme: "Chapter 8 – Object-Based Programming"— Presentation transcript:

1 Chapter 8 – Object-Based Programming
Outline Classes as User Defined Types Value-Types and Reference-Types 8.4   Controlling Access to Members 8.5   Constructors 8.6   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.15   Namespaces and Assemblies

2 Classes as User Defined Types (1) (JPF)
May be used to represent a user defined type Example: Time data type Syntactically much similar to a module Data and operations on the data are defined together Instance variables Represent the data (internal data structure) of an instance of the type Example: hour, minutes and seconds Instance methods (functions and procedures) Represent operations on instances of the type Example: change the time (procedure), convert to string (function)

3 Classes as User Defined Types (2) (JPF)
Encapsulation (private and public) Encapsulation is a fundamental principle of object orientation Instance variables are usually declared private, so that clients of the class do not have direct access to them (can only have indirect access to them via public methods) Clients of a class do not need to know its internal data structure Advantage: integrity of the data (example: 0<=hour<=23, ...) is completely controlled within the class Advantage: the internal data structure may be changed (example: time as seconds elapsed since a reference point), without affecting the clients of the class (as long as the syntax and semantics of public methods is not changed) Special methods named New (constructors) take care of initializing the instance variables of newly allocated instances (object) of the class Auxiliary internal methods should also be declared private

4 Classes as User Defined Types (3) (JPF)
Objects and variables Instances of a class are called objects An object stores the values of the instance variables A variable of class type holds a reference to an object and not the data (or object) itself This is different from what happens with a primitive type Dim i as Integer = 123 Dim t as CTime = New CTime(10,30, 0) i 123 t1 a variable of type CTime an object of type CTime

5 Value-Types and Reference-Types (JPF)
Primitive types such as Integer are value-types Variables of a value-type contain data Comparison and assignment act on values Reference types Classes (user defined or defined in the .Net class libraries) are reference-types Variable of a reference-type contain references to objects (or Nothing when no object is referenced) Objects are created with New New returns a reference to a newly allocated object The result of New is usually assigned to a variable for later use Comparison and assignment act on references

6 Value-Types and Reference-Types (JPF)
Example Dim t1 as CTime = New CTime(10,30, 0) Dim t2 as CTime = New CTime(10,30, 0) Dim t3 as Ctime = t1 if t1 = t ' dá FALSE if t1 = t3 ' dá TRUE t3 t1 t2

7 Class CTime inherits existing pieces of class Object. CTime.vb
1 ' Fig. 8.1: CTime.vb 2 ' Represents time in 24-hour format. 3 4 Class CTime Inherits Object 6 ' declare Integer instance values for hour, minute and second Private mHour As Integer ' Private mMinute As Integer ' Private mSecond As Integer ' 11 ' Method New is the CTime constructor method, which initializes ' instance variables to zero Public Sub New() SetTime(0, 0, 0) End Sub ' New 17 ' 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) 23 ' 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 30 Class CTime inherits existing pieces of class Object. CTime.vb Introduces a New constructor and constructors do not return values

8 31 ' check if minute is between 0 and 59, then set minute
If (minuteValue >= 0 AndAlso minuteValue < 60) Then mMinute = minuteValue Else mMinute = 0 End If 37 ' check if second is between 0 and 59, then set second If (secondValue >= 0 AndAlso secondValue < 60) Then mSecond = secondValue Else mSecond = 0 End If 44 End Sub ' SetTime 46 ' 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 52 ' 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 58 ' determine whether time is AM or PM If mHour < 12 Then suffix = " AM" End If 63 Error checks input values for variables hourValue, minuteValue and secondValue CTime.vb Argument 0 takes default value zero Arguments 1 and 2 take decimal number format

9 64 ' 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 70 Return String.Format(format, standardHour, mMinute, _ mSecond) & suffix End Function ' ToStandardString 74 75 End Class ' CTime CTime.vb

10 TimeTest.vb 1 ' Fig. 8.2: TimeTest.vb 2 ' Demonstrating class CTime. 3
4 Imports System.Windows.Forms ' para não ter de fazer System.Windows.Forms.MessageBox 5 6 Module modTimeTest 7 Sub Main() Dim time As CTime = New CTime() ' call CTime constructor Dim output As String 11 output = "The initial universal times is: " & _ time.ToUniversalString() & vbCrLf & _ "The initial standard time is: " & _ time.ToStandardString() 16 time.SetTime(13, 27, 6) ' set time with valid settings 18 output &= vbCrLf & vbCrLf & _ "Universal time after setTime is: " & _ time.ToUniversalString() & vbCrLf & _ "Standard time after setTime is: " & _ time.ToStandardString() 24 time.SetTime(99, 99, 99) ' set time with invalid settings 26 output &= vbCrLf & vbCrLf & _ "After attempting invalid settings: " & vbCrLf & _ "Universal time: " & time.ToUniversalString() & _ vbCrLf & "Standard time: " & time.ToStandardString() 31 MessageBox.Show(output, "Testing Class CTime") End Sub ' Main 34 35 End Module ' modTimeTest TimeTest.vb

11 TimeTest.vb

12 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 Class members that are visible can be accessed only through a “handle” (ObjectReferenceName.memberName)

13 Cannot access a Private variable
1 ' Fig. 8.3: RestrictedAccess.vb 2 ' Demonstrate error from attempt to access Private class member. 3 4 Module modRestrictedAccess 5 Sub Main() Dim time As New CTime() 8 time.mHour = 7 ' error End Sub ' Main 11 12 End Module ' modRestrictedAccess RestrictedAccess.vb Cannot access a Private variable

14 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

15 8.6 Using Overloaded Constructors
Must have different numbers and/or types and/or orders of parameters

16 1 ' Fig. 8.4: CTime2.vb 2 ' Represents time and contains overloaded constructors. 3 4 Class CTime2 Inherits Object 6 ' declare Integers for hour, minute and second Private mHour As Integer ' Private mMinute As Integer ' Private mSecond As Integer ' 11 ' constructor initializes each variable to zero and ' ensures that each CTime2 object starts in consistent state Public Sub New() SetTime() End Sub ' New 17 ' CTime2 constructor: hour supplied; ' minute and second default to 0 Public Sub New(ByVal hourValue As Integer) SetTime(hourValue) End Sub ' New 23 ' CTime2 constructor: hour and minute supplied; ' second defaulted to 0 Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer) 28 SetTime(hourValue, minuteValue) End Sub ' New 31 ' CTime2 constructor: hour, minute and second supplied Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer, ByVal secondValue As Integer) 35 CTime2.vb

17 CTime2.vb 36 SetTime(hourValue, minuteValue, secondValue)
End Sub ' New 38 ' CTime2 constructor: another CTime2 object supplied Public Sub New(ByVal timeValue As CTime2) SetTime(timeValue.mHour, timeValue.mMinute, timeValue.mSecond) End Sub ' New 43 ' set new time value using universal time; ' perform validity checks on data; ' set invalid values to zero Public Sub SetTime(Optional ByVal hourValue As Integer = 0, _ Optional ByVal minuteValue As Integer = 0, _ Optional ByVal secondValue As Integer = 0) 50 ' perform validity checks on hour, then set hour If (hourValue >= 0 AndAlso hourValue < 24) Then mHour = hourValue Else mHour = 0 End If 57 ' perform validity checks on minute, then set minute If (minuteValue >= 0 AndAlso minuteValue < 60) Then mMinute = minuteValue Else mMinute = 0 End If 64 ' perform validity checks on second, then set second If (secondValue >= 0 AndAlso secondValue < 60) Then mSecond = secondValue Else mSecond = 0 End If CTime2.vb

18 CTime2.vb 71 72 End Sub ' SetTime 73
' 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 79 ' 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 85 ' determine whether time is AM or PM If mHour < 12 Then suffix = " AM" End If 90 ' 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 97 Return String.Format(format, standardHour, mMinute, _ mSecond) & suffix End Function ' ToStandardString 101 102 End Class ' CTime2 CTime2.vb

19 TimeTest2.vb 1 ' Fig. 8.5: TimeTest2.vb
2 ' Demonstrates overloading constructors. 3 4 Imports System.Windows.Forms 5 6 Module modTimeTest2 7 Sub Main() 9 ' use overloaded constructors Dim time1 As New CTime2() Dim time2 As New CTime2(2) Dim time3 As New CTime2(21, 34) Dim time4 As New CTime2(12, 25, 42) Dim time5 As New CTime2(27, 74, 99) Dim time6 As New CTime2(time4) ' use time4 as initial value 17 Const SPACING As Integer = 13 ' spacing between output text 19 ' invoke time1 methods Dim output As String = "Constructed with: " & vbCrLf & _ " time1: all arguments defaulted" & vbCrLf & _ Space(SPACING) & time1.ToUniversalString() & _ vbCrLf & Space(SPACING) & time1.ToStandardString() 25 ' invoke time2 methods output &= vbCrLf & _ " time2: hour specified; minute and second defaulted" & _ vbCrLf & Space(SPACING) & _ time2.ToUniversalString() & vbCrLf & Space(SPACING) & _ time2.ToStandardString() 32 TimeTest2.vb

20 TimeTest2.vb 33 ' invoke time3 methods 34 output &= vbCrLf & _
" time3: hour and minute specified; second defaulted" & _ vbCrLf & Space(SPACING) & time3.ToUniversalString() & _ vbCrLf & Space(SPACING) & time3.ToStandardString() 38 ' invoke time4 methods output &= vbCrLf & _ " time4: hour, minute and second specified" & _ vbCrLf & Space(SPACING) & time4.ToUniversalString() & _ vbCrLf & Space(SPACING) & time4.ToStandardString() 44 ' invoke time5 methods output &= vbCrLf & _ " time5: hour, minute and second specified" & _ vbCrLf & Space(SPACING) & time5.ToUniversalString() & _ vbCrLf & Space(SPACING) & time5.ToStandardString() 50 ' invoke time6 methods output &= vbCrLf & _ " time6: Time2 object time4 specified" & vbCrLf & _ Space(SPACING) & time6.ToUniversalString() & _ vbCrLf & Space(SPACING) & time6.ToStandardString() 56 MessageBox.Show(output, _ "Demonstrating Overloaded Constructor") End Sub ' Main 60 61 End Module ' modTimeTest2 TimeTest2.vb

21 TimeTest2.vb

22 8.7 Properties Private and Public Get accessor Set 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

23 1 ' Fig. 8.6: CTime3.vb 2 ' Represents time in 24-hour format and contains properties. 3 4 Class CTime3 Inherits Object 6 ' declare Integers for hour, minute and second Private mHour As Integer Private mMinute As Integer Private mSecond As Integer 11 ' 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 17 ' CTime3 constructor: ' hour supplied, minute and second defaulted to 0 Public Sub New(ByVal hourValue As Integer) SetTime(hourValue, 0, 0) End Sub ' New 23 ' CTime3 constructor: ' hour and minute supplied; second defaulted to 0 Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer) 28 SetTime(hourValue, minuteValue, 0) End Sub ' New 31 ' CTime3 constructor: hour, minute and second supplied Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer, ByVal secondValue As Integer) 35 CTime3.vb

24 CTime3.vb 36 SetTime(hourValue, minuteValue, secondValue)
End Sub ' New 38 ' CTime3 constructor: another CTime3 object supplied Public Sub New(ByVal timeValue As CTime3) SetTime(timeValue.mHour, timeValue.mMinute, _ timeValue.mSecond) End Sub ' New 44 ' 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) 49 Hour = hourValue ' looks Minute = minuteValue ' dangerous Second = secondValue ' but it is correct End Sub ' SetTime 54 ' property Hour Public Property Hour() As Integer 57 ' return mHour value Get Return mHour End Get 62 ' set mHour value Set(ByVal value As Integer) 65 If (value >= 0 AndAlso value < 24) Then mHour = value Else mHour = 0 End If CTime3.vb

25 CTime3.vb 71 72 End Set 73 74 End Property ' Hour 75
' property Minute Public Property Minute() As Integer 78 ' return mMinute value Get Return mMinute End Get 83 ' set mMinute value Set(ByVal value As Integer) 86 If (value >= 0 AndAlso value < 60) Then mMinute = value Else mMinute = 0 End If 92 End Set 94 End Property ' Minute 96 ' property Second Public Property Second() As Integer 99 ' return mSecond value Get Return mSecond End Get 104 CTime3.vb

26 CTime3.vb 105 ' set mSecond value 106 Set(ByVal value As Integer) 107
If (value >= 0 AndAlso value < 60) Then mSecond = value Else mSecond = 0 End If 113 End Set 115 End Property ' Second 117 ' 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 123 ' 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 129 ' determine whether time is AM or PM If mHour < 12 Then suffix = " AM" End If 134 CTime3.vb

27 135 ' 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 141 Return String.Format(format, standardHour, mMinute, _ mSecond) & suffix End Function ' ToStandardString 145 146 End Class ' CTime3 CTime3.vb

28 TimeTest3.vb 1 ' Fig. 8.7: TimeTest3.vb 2 ' Demonstrates Properties. 3
4 Imports System.Windows.Forms 5 6 Class FrmTimeTest3 Inherits Form 8 ' Label and TextBox for hour Friend WithEvents lblSetHour As Label Friend WithEvents txtSetHour As TextBox 12 ' Label and TextBox for minute Friend WithEvents lblSetMinute As Label Friend WithEvents txtSetMinute As TextBox 16 ' Label and TextBox for second Friend WithEvents lblSetSecond As Label Friend WithEvents txtSetSecond As TextBox 20 ' Labels for outputting time Friend WithEvents lblOutput1 As Label Friend WithEvents lblOutput2 As Label 24 ' Button for adding one second to time Friend WithEvents cmdAddSecond As Button 27 Dim time As New CTime3() 29 ' Visual Studio .NET generated code 31 TimeTest3.vb

29 TimeTest3.vb 32 ' update time display 33 Private Sub UpdateDisplay()
lblOutput1.Text = "Hour: " & time.Hour & "; Minute: " & _ time.Minute & "; Second: " & time.Second 36 lblOutput2.Text = "Standard time is: " & _ time.ToStandardString & "; Universal Time is: " _ & time.ToUniversalString() End Sub ' UpdateDisplay 41 ' invoked when user presses Add Second button Protected Sub cmdAddSecond_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdAddSecond.Click 46 ' add one second time.Second = (time.Second + 1) Mod 60 txtSetSecond.Text = time.Second 50 ' add one minute if 60 seconds have passed If time.Second = 0 Then time.Minute = (time.Minute + 1) Mod 60 txtSetMinute.Text = time.Minute 55 ' 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 61 End If 63 UpdateDisplay() End Sub ' cmdAddSecond_Click 66 TimeTest3.vb

30 TimeTest3.vb 67 ' handle event when txtSetHour's text changes
Protected Sub txtSetHour_TextChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles txtSetHour.TextChanged 71 time.Hour = Convert.ToInt32(txtSetHour.Text) UpdateDisplay() End Sub ' txtSetHour_TextChanged 75 ' handle event when txtSetMinute's text changes Protected Sub txtSetMinute_TextChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles txtSetMinute.TextChanged 80 time.Minute = Convert.ToInt32(txtSetMinute.Text) UpdateDisplay() End Sub ' txtSetMinute_TextChanged 84 ' handle event when txtSetSecond's text changes Protected Sub txtSetSecond_TextChanged(ByVal sender _ As System.Object, ByVal e As System.EventArgs) _ Handles txtSetSecond.TextChanged 89 time.Second = Convert.ToInt32(txtSetSecond.Text) UpdateDisplay() End Sub ' txtSetSecond_TextChanged 93 94 End Class ' FrmTimeTest3 TimeTest3.vb

31 TimeTest3.vb

32 8.8 Composition: Objects as Instance Variables of Other Classes
Referencing Existing Objects Software Reuse: A form of composition is software reuse

33 CDay.vb 1 ' Fig. 8.8: CDay.vb 2 ' Encapsulates month, day and year. 3
4 Imports System.Windows.Forms 5 6 Class CDay Inherits Object 8 Private mMonth As Integer ' 1-12 Private mDay As Integer ' 1-31 based on month Private mYear As Integer ' any year 12 ' 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) 17 ' ensure month value is valid If (monthValue > 0 AndAlso monthValue <= 12) Then mMonth = monthValue Else mMonth = 1 23 ' inform user of error Dim errorMessage As String = _ "Month invalid. Set to month 1." 27 MessageBox.Show(errorMessage, "", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End If 31 mYear = yearValue mDay = CheckDay(dayValue) ' validate day 34 End Sub ' New CDay.vb

34 CDay.vb 36 37 ' confirm proper day value based on month and year
Private Function CheckDay(ByVal testDayValue As Integer) _ As Integer 40 Dim daysPerMonth() As Integer = _ {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 43 If (testDayValue > 0 AndAlso _ testDayValue <= daysPerMonth(mMonth)) Then 46 Return testDayValue End If 49 ' 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 54 Return testDayValue Else 57 ' inform user of error Dim errorMessage As String = _ "day " & testDayValue & "invalid. Set to day 1. " 61 MessageBox.Show(errorMessage, "", _ MessageBoxButtons.OK, MessageBoxIcon.Error) 64 Return 1 ' leave object in consistent state End If 67 End Function ' CheckDay 69 CDay.vb

35 CDay.vb 70 ' create string containing month/day/year format
Public Function ToStandardString() As String Return mMonth & "/" & mDay & "/" & mYear End Function ' ToStandardString 74 75 End Class ' CDay CDay.vb

36 CEmployee.vb 1 ' Fig. 8.9: CEmployee.vb
2 ' Represent employee name, birthday and hire date. 3 4 Class CEmployee Inherits Object 6 Private mFirstName As String Private mLastName As String Private mBirthDate As CDay ' member object reference Private mHireDate As CDay ' member object reference 11 ' CEmployee constructor Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String, _ ByVal birthMonthValue As Integer, _ ByVal birthDayValue As Integer, _ ByVal birthYearValue As Integer, _ ByVal hireMonthValue As Integer, _ ByVal hireDayValue As Integer, _ ByVal hireYearValue As Integer) 21 mFirstName = firstNameValue mLastName = lastNameValue 24 ' create CDay instance for employee birthday mBirthDate = New CDay(birthMonthValue, birthDayValue, _ birthYearValue) 28 ' create CDay instance for employee hire date mHireDate = New CDay(hireMonthValue, hireDayValue, _ hireYearValue) End Sub ' New 33 CEmployee.vb

37 34 ' return employee information as standard-format String
Public Function ToStandardString() As String Return mLastName & ", " & mFirstName & " Hired: " _ & mHireDate.ToStandardString() & " Birthday: " & _ mBirthDate.ToStandardString() End Function ' ToStandardString 40 41 End Class ' CEmployee CEmployee.vb

38 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 Sub Main() Dim employee As New CEmployee( _ "Bob", "Jones", 7, 24, 1949, 3, 12, 1988) 11 MessageBox.Show(employee.ToStandardString(), _ "Testing Class Employee") End Sub ' Main 15 16 End Module ' modCompositionTest CompositionTest.vb

39 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

40 Reference Me can refer to any instance variable explicitly
1 ' Fig. 8.11: CTime4.vb 2 ' Encapsulate time using Me reference. 3 4 Class CTime4 Private mHour, mMinute, mSecond As Integer 6 ' CTime4 constructor Public Sub New(ByVal mHour As Integer, _ ByVal mMinute As Integer, ByVal mSecond As Integer) 10 Me.mHour = mHour Me.mMinute = mMinute Me.mSecond = mSecond End Sub ' New 15 ' create String using Me and implicit references Public Function BuildString() As String Return "Me.ToUniversalString(): " & Me.ToUniversalString() _ & vbCrLf & "ToUniversalString(): " & ToUniversalString() End Function ' BuildString 21 ' convert to String in standard-time format Public Function ToUniversalString() As String Return String.Format("{0:D2}:{1:D2}:{2:D2}", _ mHour, mMinute, mSecond) End Function ' ToUniversalString 27 28 End Class ' CTime4 CTime4.vb Reference Me can refer to any instance variable explicitly Uses reference Me explicitly Uses reference Me implicitly

41 MeTest.vb 1 ' Fig. 8.12: MeTest.vb 2 ' Demonstrates Me reference. 3
4 Imports System.Windows.Forms 5 6 Module modMeTest 7 Sub Main() Dim time As New CTime4(12, 30, 19) 10 MessageBox.Show(time.BuildString(), _ "Demonstrating the 'Me' Reference") End Sub ' Main 14 15 End Module ' modMeTest MeTest.vb

42 * Finalizer methods Finalizer method performs termination housekeeping on that object just before the garbage collector reclaims the object's memory.

43 Accessed with ClassName.SharedMemberName
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 Class Method have no Me reference Accessed with ClassName.SharedMemberName

44 Initializes mCount to 0 by default
1 ' Fig. 8.13: CEmployee2.vb 2 ' Class CEmployee2 uses Shared variable. 3 4 Class CEmployee2 Inherits Object 6 Private mFirstName As String Private mLastName As String 9 ' number of objects in memory Private Shared mCount As Integer 12 ' CEmployee2 constructor Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String) 16 mFirstName = firstNameValue mLastName = lastNameValue 19 mCount += 1 ' increment shared count of employees Console.WriteLine _ ("Employee object constructor: " & mFirstName & _ " " & mLastName) End Sub ' New 25 ' 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 33 CEmployee2.vb Initializes mCount to 0 by default CEmployee2 constructor increments mCount Finalize method decrements mCount

45 Member mCount can be referenced without declaring a CEmployee2 object
' return first name Public ReadOnly Property FirstName() As String 36 Get Return mFirstName End Get 40 End Property ' FirstName 42 ' return last name Public ReadOnly Property LastName() As String 45 Get Return mLastName End Get 49 End Property ' LastName 51 ' property Count Public ReadOnly Shared Property Count() As Integer 54 Get Return mCount End Get 58 End Property ' Count 60 61 End Class ' CEmployee2 CEmployee2.vb Member mCount can be referenced without declaring a CEmployee2 object

46 Sets objects’ references to Nothing
1 ' Fig. 8.14: SharedTest.vb 2 ' Demonstrates Shared members. 3 4 Imports System.Windows.Forms 5 6 Module modSharedTest 7 Sub Main() Dim output As String 10 Console.WriteLine("Employees before instantiation: " & _ CEmployee2.Count) 13 Dim employee1 As CEmployee2 = _ New CEmployee2("Susan", "Baker") 16 Dim employee2 As CEmployee2 = _ New CEmployee2("Bob", "Jones") 19 ' output of employee2 after instantiation Console.WriteLine(vbCrLf & _ "Employees after instantiation: " & vbCrLf & _ "via Employee.Count: " & CEmployee2.Count) 24 ' display name of first and second employee Console.WriteLine(vbCrLf & "Employees 1: " & _ employee1.FirstName & " " & employee1.LastName & _ vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ employee2.LastName) 30 ' mark employee1 and employee2 for garbage collection employee1 = Nothing employee2 = Nothing 34 SharedTest.vb Declares two CEmployee2 objects and increments mCount by two Sets objects’ references to Nothing

47 SharedTest.vb 35 System.GC.Collect() ' request garbage collection
End Sub ' Main 37 38 End Module ' modShared 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

48 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

49 CCircleConstants.vb 1 ' Fig. 8.15: CCircleConstants.vb
2 ' Encapsulate constants PI and radius. 3 4 Class CCircleConstants 5 ' PI is constant data member Public Const PI As Double = 8 ' radius is uninitialized constant Public ReadOnly RADIUS As Integer 11 ' constructor of class CCircleConstants Public Sub New(ByVal radiusValue As Integer) RADIUS = radiusValue End Sub ' New 16 17 End Class ' CCircleConstants CCircleConstants.vb

50 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 Sub Main() Dim random As Random = New Random() Dim circle As CCircleConstants = _ New CCircleConstants(random.Next(1, 20)) 12 Dim radius As String = Convert.ToString(circle.RADIUS) 14 Dim output As String = "Radius = " & radius & vbCrLf _ & "Circumference = " + String.Format("{0:N3}", _ circle.RADIUS * 2 * CCircleConstants.PI) 18 MessageBox.Show(output, "Circumference", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 22 23 End Module ' modConstAndReadOnly ConstAndReadOnly.vb

51 8.15 Namespaces and Assemblies
.NET 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 By default, every executable file you create with Visual Basic .NET contains a namespace with the same name as your project. For example, if you define an object within a project named ListBoxProject, the executable file, ListBoxProject.exe, contains a namespace called ListBoxProject. If you use the Imports statement without an alias, you can use all the names in that namespace without qualification provided they are unique to the project.

52 CEmployee3.vb 1 ' Fig. 8.17: CEmployee3.vb
2 ' Class CEmployee3 uses Shared variable. 3 4 Public Class CEmployee3 Inherits Object 6 Private mFirstName As String Private mLastName As String 9 ' number of objects in memory Private Shared mCount As Integer 12 ' CEmployee3 constructor Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String) 16 mFirstName = firstNameValue mLastName = lastNameValue 19 mCount += 1 ' increment shared count of employees Console.WriteLine _ ("Employee object constructor: " & mFirstName & _ " " & mLastName) End Sub ' New 25 ' 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 33 CEmployee3.vb

53 CEmployee3.vb 34 ' return first name
Public ReadOnly Property FirstName() As String 36 Get Return mFirstName End Get 40 End Property ' FirstName 42 ' return last name Public ReadOnly Property LastName() As String 45 Get Return mLastName End Get 49 End Property ' LastName 51 ' property Count Public ReadOnly Shared Property Count() As Integer 54 Get Return mCount End Get 58 End Property ' Count 60 61 End Class ' CEmployee3 CEmployee3.vb

54 8.15 Namespaces Fig Simple Class Library.

55 The module imports class CEmployee3
1 ' Fig. 8.19: AssemblyTest.vb 2 ' Demonstrates assembly files and namespaces. 3 4 Imports EmployeeLibrary ' contains class CEmployee3 5 6 Module modAssemblyTest 7 Public Sub Main() Dim output As String 10 Console.WriteLine("Employees before instantiation: " & _ CEmployee3.Count) 13 Dim employee1 As CEmployee3 = _ New CEmployee3("Susan", "Baker") 16 Dim employee2 As CEmployee3 = _ New CEmployee3("Bob", "Jones") 19 ' output of employee after instantiation Console.WriteLine(vbCrLf & "Employees after instantiation:" _ & vbCrLf & "via Employee.Count: " & CEmployee3.Count) 23 ' display name of first and second employee Console.WriteLine(vbCrLf & "Employees 1: " & _ employee1.FirstName & " " & employee1.LastName & _ vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ employee2.LastName) 29 ' mark employee1 and employee2 for garbage collection employee1 = Nothing employee2 = Nothing 33 AssemblyTest.vb The module imports class CEmployee3

56 AssemblyTest.vb 34 System.GC.Collect() ' request garbage collection
End Sub ' Main 36 37 End Module ' modAssemblyTest 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

57 * 8.16 Class View and Object Browser
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

58 8.16 Class View and Object Browser
Fig Class View of Fig. 8.1 and Fig. 8.2.

59 8.16 Class View and Object Browser
Fig Object Browser when user selects Object from CTime.vb,

60 8.16 Class View and Object Browser
Fig Object Browser when user selects Object from CTime.vb,

61 Classes as Real World Concepts (JPF)
Examples in a banking application: Customer holds data about a customer (number, name, address, ...) provides operations on customers (create, update the address, query accounts, ...) Account holds data about an account (number, owners, movements, balance, ...) provides operations on accounts (create, deposit, withdrawal, query movements, query balance, query owners, ...) Related with each other


Download ppt "Chapter 8 – Object-Based Programming"

Similar presentations


Ads by Google