1 / 32

8.3 Class Scope

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

Download Presentation

8.3 Class Scope

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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 6 Sub Main() 7 Dim time As New CTime() 8 9 time.mHour = 7' error 10 End Sub ' Main 11 12 End Module' modRestrictedAccess RestrictedAccess.vb

  4. 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

  5. 8.6 Using Overloaded Constructors • Overloaded Constructors • Must have different numbers and/or types and/or orders of parameters

  6. Initialize Private vaiables mHour, mMinute and mSecond to 0 Declares CTime2 constructor with one argument of hourValue Declares CTime2 constructor with three arguments of hourValue, minuteValuesecondValue Declares CTime2 constructor with twoarguments of hourValue and minuteValue 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 AsInteger) 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 CTime2.vb

  7. Values of mHour, mMinute, and mSecond are initialized when supplied Error checks input values for variables hourValue, minuteValue, and secondValue 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(OptionalByVal hourValue As Integer = 0, _ 48 OptionalByVal minuteValue AsInteger = 0, _ 49 OptionalByVal secondValue As Integer = 0) 50 51 ' perform validity checks on hour, then set hour 52 If (hourValue >= 0AndAlso 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 >= 0AndAlso 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 >= 0AndAlso secondValue < 60) Then 67 mSecond = secondValue 68 Else 69 mSecond = 0 70 End If CTime2.vb

  8. 0’s are placed for everymissing values to satisfy SetTimes’s requirement 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 < 12Then 88 suffix = " AM" 89 End If 90 91 ' convert from universal-time format to standard-time format 92 If (mHour = 12OrElse mHour = 0) Then 93 standardHour = 12 94 Else 95 standardHour = mHour Mod12 96 End If 97 98 Return String.Format(format, standardHour, mMinute, _ 99 mSecond) & suffix 100 End Function ' ToStandardString 101 102 End Class' CTime2 CTime2.vb

  9. Declares six different CTime objects that invoke various constructors of different class Time1 constructor has necessary number of arguments to be invoked 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 ConstSPACINGAs 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 TimeTest2.vb

  10. Shows the output in MessageBox.Show 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 TimeTest2.vb

  11. 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

  12. 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 CTime3.vb

  13. Defines the properties Hour of class CTime3 Error checks bogus input for variable mHour 36 SetTime(hourValue, minuteValue, secondValue) 37 EndSub ' 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 >= 0AndAlso value < 24) Then 67 mHour = value 68 Else 69 mHour = 0 70 End If CTime3.vb

  14. 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 EndGet 83 84 ' set mMinute value 85 Set(ByVal value As Integer) 86 87 If (value >= 0AndAlso 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 CTime3.vb Defines the properties for Minute and error checks for erroneous input for variable value Sets variable mMinute to value

  15. Checks for erroneous input for variable value Sets variable mSecond to value 105 ' set mSecond value 106 Set(ByVal value As Integer) 107 108 If (value >= 0AndAlso 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 < 12Then 132 suffix = " AM" 133 End If 134 CTime3.vb

  16. 135 ' convert from universal-time format to standard-time format 136 If (mHour = 12OrElse mHour = 0) Then 137 standardHour = 12 138 Else 139 standardHour = mHour Mod12 140 End If 141 142 Return String.Format(format, standardHour, mMinute, _ 143 mSecond) & suffix 144 End Function ' ToStandardString 145 146 End Class' CTime3 CTime3.vb

  17. Declares three methods that use Hour, Minute and Second properties of CTime3 Object to alter time values 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 TimeTest3.vb

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

  19. Declares three integers mMonth, mDay, and mYear Constructor that receives three arguments Assigns values to class variables mMonth, mDay, mYear after error checking 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 AsInteger' 1-12 10 Private mDay AsInteger' 1-31 based on month 11 Private mYear AsInteger' 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 > 0AndAlso 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 CDay.vb

  20. 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 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 CEmployee.vb

  21. 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

  22. 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 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 CTime4.vb

  23. 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.

  24. 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

  25. Declares PI as a constant variable Declares RADIUS as a ReadOnly variable 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 ConstPIAs Double = 3.14159 8 9 ' radius is uninitialized constant 10 Public ReadOnlyRADIUSAs 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 CCircleConstants.vb

  26. 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

  27. 8.14 Software Reusability • Rapid application development (RAD) • Software reusability • Software reusability speeds the development of powerful, high quality software.

  28. 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

  29. 9.4 Relationship Between Base Classes and Derived Classes • Structural Inheritance • Base Class • Base-class must be declared as overridable if that method is to be overridden in the derived class • The base-class should be able to change its implementation freely • Derived Class • Derived-class object can assign an illegal value to the Protected data, hence leaving the object in an inconsistent state • Derived-classes should depend only on the base-classes services (non private methods and properties)

  30. 9.6 Constructors and Finalizers in Derived Classes • Constructors in Derived Classes • Base-class • Base-class constructors are not inherited by derived classes • Each base-class constructor initializes the base-class instance variables that the derived-class object inherits • Finalizers in Derived Classes • Derived Classes • Executing the finalizer method should free all resources acquired by the object before the garbage collector reclaims memory for that object • Keyword MyBase is used to invoke the finalizer of the base class

  31. Me implicitly invokes the class’s ToStringmethod to obtain the String representation of CPoint3’s coordinates Calls method Finalize explicitly 1 ' Fig. 9.16: Point3.vb 2 ' CPoint3 class represents an x-y coordinate pair. 3 4 Public Class CPoint3 5 6 ' point coordinate 7 Private mX, mY As Integer 8 9 ' default constructor 10 Public Sub New() 11 12 ' implicit call to Object constructor occurs here 13 X = 0 14 Y = 0 15 Console.Writeline("CPoint3 constructor: {0}", Me) 16 End Sub ' New 17 18 ' constructor 19 Public Sub New(ByVal xValue As Integer,_ 20 ByVal yValue As Integer) 21 22 ' implicit call to Object constructor occurs here 23 X = xValue 24 Y = yValue 25 Console.Writeline("CPoint3 constructor: {0}", Me) 26 End Sub ' New 27 28 ' finalizer overrides version in class Object 29 Protected Overrides Sub Finalize() 30 Console.Writeline("CPoint3 Finalizer: {0}", Me) 31 MyBase.Finalize() ' call Object finalizer 32 End Sub ' Finalize 33 Point3.vb

  32. 9.7 Software Engineering with Inheritance • Inheritance • Class • New classes inherit old classes, hence this method allows programmers to practice software reuse

More Related