Chapter 8 Object-Based Programming 389 the Time1object to (Web server version)

Chapter 8 Object-Based Programming 389 the Time1object to which timerefers. When this program is compiled, the compiler generates an error stating that the privatemember houris not accessible. [Note: This program assumes that the Time1class from Figure 8.1 is used.] Good Programming Practice 8.3 Our preference is to list the private instance variables of a class first, so that, as you read the code, you see the names and types of the instance variables before they are used in the methods of the class. Software Engineering Observation 8.9 Keep all the instance variables of a class private. When necessary, provide public methods to set the values of private instance variables and to get the values of private instance variables. This architecture helps hide the implementation of a class from its clients, which reduces bugs and improves program modifiability. Access to private data should be controlled carefully by the class s methods. For example, to allow clients to read the value of privatedata, the class can provide a get method (also called an accessor method). To enable clients to modify private data, the class can provide a set method (also called a mutator method). Such modification would seem to violate the notion of privatedata, but a set method can provide data validation capabilities (such as range checking) to ensure that the value is set properly. A set method can also translate between the form of the data used in the interface and the form used in the implementation. A get method need not expose the data in raw format; rather, the get method can edit the data and limit the view of the data the client will see. Software Engineering Observation 8.10 Class designers use private data and public methods to enforce the notion of information hiding and the principle of least privilege. If the client of a class needs access to data in the class, provide that access through public methods of the class. By doing so, the programmer of the class controls how the class s data is manipulated (e.g., data validity checking can prevent invalid data from being stored in an object). This is the principle of data encapsulation. 1 // Fig. 8.3: TimeTest2.java 2 // Demonstrate errors resulting from attempts 3 // to access private members of class Time1. 4 public class TimeTest2 { 5 6 public static void main( String args[] ) 7 { 8 Time1 time = new Time1(); 9 10 time.hour = 7; 11 } 12 } TimeTest2.java:10: hour has private access in Time1 time.hour = 7; ^ 1 error Fig. 8.3Erroneous attempt to access private members of class Time1. Fig. 8. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision mysql5 web hosting services

Leave a Reply