Vps web hosting - Chapter 8 Object-Based Programming 401 although set and

Chapter 8 Object-Based Programming 401 although set and get methods could provide access to private data, the access is restricted by the programmer s implementation of the methods. The benefits of data integrity are not automatic simply because instance variables are made private the programmer must provide validity checking. Java provides the framework in which programmers can design better programs in a convenient manner. Software Engineering Observation 8.15 Methods that set the values of private data should verify that the intended new values are proper; if they are not, the set methods should place the private instance variables into an appropriate consistent state. A class s set methods can return values indicating that attempts were made to assign invalid data to objects of the class. This enables clients of the class to test the return values of set methods to determine whether the objects they are manipulating are valid and to take appropriate action if the objects are not valid. In Chapter 14, Exception Handling, we illustrate a more robust way in which clients of a class can be notified if an object is not valid. Good Programming Practice 8.5 Every method that modifies the private instance variables of an object should ensure that the data remains in a consistent state. The applet of Fig. 8.8 (class Time3) and Fig. 8.9 (class TimeTest5) enhances our Timeclass (now called Time3) to include get and set methods for the hour, minuteand secondprivate instance variables. The set methods strictly control the setting of the instance variables to valid values. Attempts to set any instance variable to an incorrect value cause the instance variable to be set to zero (thus leaving the instance variable in a consistent state). Each get method simply returns the appropriate instance variable s value. This applet introduces enhanced GUI event handling techniques as we move toward defining our first full-fledged windowed application. After discussing the code, we introduce how to set up an applet to use classes in programmer-defined packages. 1 // Fig. 8.8: Time3.java 2 // Time3 class definition with set and get methods 3 package com.deitel.jhtp4.ch08; 4 5 // Java core packages 6 import java.text.DecimalFormat; 7 8 public class Time3 extends Object { 9 private int hour; // 0 - 23 10 private int minute; // 0 - 59 11 private int second; // 0 - 59 12 13 // Time3 constructor initializes each instance variable 14 // to zero. Ensures that Time object starts in a 15 // consistent state. 16 public Time3() 17 { 18 setTime( 0, 0, 0 ); 19 } Fig. 8.8 Class Time3with set and get methods (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply