Domain and web hosting - 396 Object-Based Programming Chapter 8 overloads the constructor
396 Object-Based Programming Chapter 8 overloads the constructor method to provide a convenient variety of ways to initialize objects of the new class Time2. The constructors guarantee that every object begins its existence in a consistent state. In this program, each constructor calls method setTime with the values passed to the constructor, to ensure that the value supplied for houris in the range 0 to 23 and that the values for minuteand secondare each in the range 0 to 59. If a value is out of range, it is set to zero by setTime(once again ensuring that each instance variable remains in a consistent state). The appropriate constructor is invoked by matching the number, types and order of the arguments specified in the constructor call with the number, types and order of the parameters specified in each constructor definition. The matching constructor is called automatically. Figure 8.7 uses class Time2 to demonstrate its constructors. 1 // Fig. 8.6: Time2.java 2 // Time2 class definition with overloaded constructors. 3 package com.deitel.jhtp4.ch08; 4 5 // Java core packages 6 import java.text.DecimalFormat; 7 8 public class Time2 extends Object { 9 private int hour; // 0 - 23 10 private int minute; // 0 - 59 11 private int second; // 0 - 59 12 13 // Time2 constructor initializes each instance variable 14 // to zero. Ensures that Time object starts in a 15 // consistent state. 16 public Time2() 17 { 18 setTime( 0, 0, 0 ); 19 } 20 21 // Time2 constructor: hour supplied, minute and second 22 // defaulted to 0 23 public Time2( int h ) 24 { 25 setTime( h, 0, 0 ); 26 } 27 28 // Time2 constructor: hour and minute supplied, second 29 // defaulted to 0 30 public Time2( int h, int m ) 31 { 32 setTime( h, m, 0 ); 33 } 34 35 // Time2 constructor: hour, minute and second supplied 36 public Time2( int h, int m, int s ) 37 { 38 setTime( h, m, s ); 39 } Fig. 8.6 Class Time2with overloaded constructors (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision virtual web hosting services