Chapter 8 (Web hosting account) Object-Based Programming 291 As previously stated,
Chapter 8 Object-Based Programming 291 As previously stated, publicmethods present to the class s clients a view of the services that the class provides (i.e., the publicinterface of the class). Previously, we mentioned the merits of writing methods that perform only one task. If a method must execute other tasks to calculate its final result, these tasks should be performed by a helper method. A client does not need to call these helper methods, nor does it need to be concerned with how the class uses its helper methods. For these reasons, helper methods are declared as privatemembers of a class. Common Programming Error 8.2 Attempting to access a private class member from outside that class is a compiler error. The application of Fig. 8.3 (which uses the Time1 class from Fig. 8.1) demonstrates that privateclass members are not accessible outside the class. Lines 12 14 attempt to access the privateinstance variables hour, minuteand secondof the Time1object to which timerefers. When this program is compiled, the compiler generates errors stating that the privatemembers hour, minuteand secondare not accessible. Access to privatedata should be controlled carefully by a class s methods. To allow clients to read the values of private data, the class can define a property that enables client code to access this private data safely. Properties, which we discuss in detail in Section 8.7, contain accessor methods that handle the details of modifying and returning data. A property definition can contain a get accessor, a set accessor or both. A get accessor enables a client to read a privatedata value; a setaccessor enables the client to modify that value. Such modification would seem to violate the notion of private data. However, a set accessor can provide data-validation capabilities (such as range checking) to ensure that the value is set properly. A set accessor also can translate between the format of the data used in the interface and the format used in the underlying implementation. Similarly, a get accessor need not expose the data in raw format; rather, the getaccessor can edit the data and limit the client s view of that data. 1 // Fig. 8.3: RestrictedAccess.cs 2 // Demonstrate compiler errors from attempt to access 3 // private class members. 4 5 class RestrictedAccess 6 { 7 // main entry point for application 8 static void Main( string[] args ) 9 { 10 Time1 time = new Time1(); 11 12 time.hour = 7; 13 time.minute = 15; 14 time.second = 30; 15 } 16 17 } // end class RestrictedAccess Fig. 8.3 Fig. 8.3Fig. 8.FiFi3g. 8.3g. 8.3Accessing privateclass members from client code generates syntax errors. (Part 1 of 2.)
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.