Controlling Access to Members

The access modifiers public and private control access to a class's variables and methods. (In Section 9.15 and Chapter 10, we will introduce the additional access modifiers internal and protected, respectively.) As we stated in Section 9.2, the primary purpose of public methods is to present to the class's clients a view of the services the class provides (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 and methods (i.e., the class's implementation details) are not directly accessible to the class's clients.

Figure 9.3 demonstrates that private class members are not directly accessible outside the class. Lines 911 attempt to access directly private instance variables hour, minute and second of Time1 object time. When this application is compiled, the compiler generates error messages stating that these private members are not accessible. [Note: This application assumes that the Time1 class from Fig. 9.1 is used.]

Figure 9.3. Private members of class Time1 are not accessible.

1 // Fig. 9.3: MemberAccessTest.cs 2 // Private members of class Time1 are not accessible. 3 public class MemberAccessTest 4 { 5 public static void Main( string[] args ) 6 { 7 Time1 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 } // end Main 13 } // end class MemberAccessTest  

Common Programming Error 9 1

An attempt by a method that is not a member of a class to access a private member of that class is a compilation error.

Notice that members of a classfor instance, methods and instance variablesdo not need to be explicitly declared private. If a class member is not declared with an access modifier, it has private access by default. We always explicitly declare private members.

Referring to the Current Object s Members with the this Reference

Категории