F.3. Controlling Access to Members

The access modifiers public and private control access to a class’s variables and methods. In Appendix G, we’ll introduce the access modifier protected. As you know, 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 need not be concerned with how the class accomplishes its tasks. For this reason, the class’s private variables and private methods (i.e., its implementation details) are not accessible to its clients.

Figure F.3 demonstrates that private class members are not accessible outside the class. Lines 9–11 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 that these private members are not accessible. This program assumes that the Time1 class from Fig. F.1 is used.


 1   // Fig. F.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

MemberAccessTest.java:9: hour has private access in Time1
      time.hour = 7; // error: hour has private access in Time1
          ^
MemberAccessTest.java:10: minute has private access in Time1
      time.minute = 15; // error: minute has private access in Time1
          ^
MemberAccessTest.java:11: second has private access in Time1
      time.second = 30; // error: second has private access in Time1
          ^
3 errors


Fig. F.3 | Private members of class Time1 are not accessible.

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

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