Controlling Access to Members
The access modifiers public and private control access to a class's variables and methods. (In Chapter 9, we will introduce the additional access modifier protected.) As we stated in Section 8.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, the private variables and private methods of a class (i.e., the class's implementation details) are not directly accessible to the class's clients.
Figure 8.3 demonstrates that private class members are not directly accessible outside the class. Lines 911 attempt to access directly the private instance variables hour, minute and second of the Time1 object time. When this program is compiled, the compiler generates error messages stating that these private members are not accessible. [Note: This program assumes that the Time1 class from Fig. 8.1 is used.]
Figure 8.3. Private members of class Time1 are not accessible.
1 // Fig. 8.3: MemberAccessTest.java 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 8.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. |