10.3 Controlling Access to Members

The access modifiers public and private control access to a class’s variables, methods and properties. (In Chapter 11, we’ll introduce the additional access modifier protected.) As we stated in Section 10.2, the primary purpose of public methods and properties is to present to the class’s clients a view of the services the class provides (that is, the class’s public interface). Clients of the class need not be concerned with how the class accomplishes its tasks. For this reason, a class’s private variables, properties and methods (i.e., the class’s implementation details) are not directly accessible to the class’s clients.

Figure 10.3 demonstrates that private class members are not directly accessible outside the class. In this app, we use a modified version of class Time1 that declares private instance variables hour, minute and second, rather than public properties Hour, Minute and Second. Lines 9–11 attempt to directly access private instance variables hour, minute and second of Time1 object time. When this app is compiled, the compiler generates error messages stating that these private members are not accessible.

Fig. 10.3 Private members of class Time1 are not accessible outside the class.

Alternate View

 1    // Fig. 10.3: MemberAccessTest.cs
 2    // Private members of class Time1 are not accessible outside the class.
 3    class MemberAccessTest
 4    {
 5       static void Main()
 6       {
 7          var time = new Time1(); // create and initialize Time1 object
 8
 9          time.hour = 7; // error: hour has private access in Time1
10          time.minute = 15; // error: minute has private access in Time1
11          time.second = 30; // error: second has private access in Time1
12       }
13    }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset