Archive for April, 2007

398 Object-Based Programming (Make my own web site) Chapter 8 of the constructors

Monday, April 30th, 2007

398 Object-Based Programming Chapter 8 of the constructors receive values for the hour, minuteand second, all the constructors call setTime with values for hour, minute and second and substitute zeros for the missing values to satisfy setTime s requirement of three arguments. Notice in particular the constructor at lines 42 45, which uses the hour, minuteand secondvalues of its argument timeto initialize the new Time2object. Even though we know that hour, minute and second are declared as private variables of class Time2, we are able to access these values directly by using the expressions time.hour, time.minuteand time.second. This is due to a special relationship between objects of the same class. When one object of a class has a reference to another object of the same class, the first object can access all the second object s data and methods. Class TimeTest4(Fig. 8.7) creates six Time2objects (lines 17 22) to demonstrate how to invoke the different constructors of the class. Line 17 shows that the no-argument constructor is invoked by placing an empty set of parentheses after the class name when allocating a Time2 object with new. Lines 18 22 of the program demonstrate passing arguments to the Time2 constructors. Remember that 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 method definition. So, line 18 invokes the constructor at line 23 of Fig. 8.6. Line 19 invokes the constructor at line 30 of Fig. 8.6. Lines 20 21 invoke the constructor at line 36 of Fig. 8.6. Line 22 invokes the constructor at line 42 of Fig. 8.6. Note that each Time2constructor in Fig. 8.6 could be written to include a copy of the appropriate statements from method setTime. This could be slightly more efficient, because the extra call to setTime is eliminated. However, consider changing the representation of the time from three intvalues (requiring 12 bytes of memory) to a single int value representing the total number of seconds that have elapsed in the day (requiring 4 bytes of memory). Coding the Time2 constructors and method setTime identically makes such a change in this class definition more difficult. If the implementation of method setTimechanges, the implementation of the Time2constructors would need to change accordingly. Having the Time2constructors call setTimedirectly requires any changes to the implementation of setTimeto be made only once. This reduces the likelihood of a programming error when altering the implementation. Software Engineering Observation 8.14 If a method of a class already provides all or part of the functionality required by a constructor (or other method) of the class, call that method from the constructor (or other method). This simplifies the maintenance of the code and reduces the likelihood of an error if the implementation of the code is modified. It is also an effective example of reuse. 1 // Fig. 8.7: TimeTest4.java 2 // Using overloaded constructors 3 4 // Java extension packages 5 import javax.swing.*; 6 Fig. 8.7Using overloaded constructors to initialize objects of class Time2(part 1 Fig. of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision mysql hosting services

Chapter 8 Object-Based Programming 397 40 41 // (Web hosting control panel)

Monday, April 30th, 2007

Chapter 8 Object-Based Programming 397 40 41 // Time2 constructor: another Time2 object supplied 42 public Time2( Time2 time ) 43 { 44 setTime( time.hour, time.minute, time.second ); 45 } 46 47 // Set a new time value using universal time. Perform 48 // validity checks on data. Set invalid values to zero. 49 public void setTime( int h, int m, int s ) 50 { 51 hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 52 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); 53 second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 54 } 55 56 // convert to String in universal-time format 57 public String toUniversalString() 58 { 59 DecimalFormat twoDigits = new DecimalFormat( "00" ); 60 61 return twoDigits.format( hour ) + ":" + 62 twoDigits.format( minute ) + ":" + 63 twoDigits.format( second ); 64 } 65 66 // convert to String in standard-time format 67 public String toString() 68 { 69 DecimalFormat twoDigits = new DecimalFormat( "00" ); 70 71 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + 72 ":" + twoDigits.format( minute ) + 73 ":" + twoDigits.format( second ) + 74 ( hour < 12 ? " AM" : " PM" ); 75 } 76 77 } // end class Time2 Fig. 8.6 Class Time2with overloaded constructors (part 2 of 2). Most of the code in class Time2is identical to that in class Time1, so we concentrate on only the new features here (i.e., the constructors). Lines 16 19 define the no-argument (default) constructor. Lines 23 26 define a Time2 constructor that receives a single int argument representing the hour. Lines 30 33 defines a Time2 constructor that receives two intarguments representing the hourand minute. Lines 36 39 define a Time2constructor that receives three intarguments representing the hour, minuteand second. Lines 42 45 define a Time2constructor that receives a Time2reference to another Time2 object. In this case, the values from the Time2 argument are used to initialize the hour, minute and second. Notice that none of the constructors specifies a return data type (remember, this is not allowed for constructors). Also, notice that all the constructors receive different numbers of arguments and/or different types of arguments. Even though only two Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for high quality webhost to host and run your jsp application check Vision florida web design services

Domain and web hosting - 396 Object-Based Programming Chapter 8 overloads the constructor

Monday, April 30th, 2007

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

Web site hosting - Chapter 8 Object-Based Programming 395 grammer of a

Sunday, April 29th, 2007

Chapter 8 Object-Based Programming 395 grammer of a class can define the class s constructor, which is invoked each time the program instantiates an object of that class. Instance variables can be initialized implicitly to their default values (0for primitive numeric types, false for booleans and null for references), they can be initialized in a constructor of the class or their values can be set later after the object is created. Constructors cannot specify return types or return values. A class can contain overloaded constructors to provide a variety of means for initializing objects of that class. When a program instantiates an object of a class, the program can supply initializers in parentheses to the right of the class name. These initializers are passed as arguments to the class s constructor. This technique is demonstrated in the example of Section 8.7. We have also seen this technique several times previously as we created new objects of classes like DecimalFormat, JLabel, JTextField, JTextArea and JButton. For each of these classes, we have seen statements of the form ref = new ClassName( arguments ); where ref is a reference of the appropriate data type, new indicates that a new object is being created, ClassName indicates the type of the new object and arguments specifies the values used by the class s constructor to initialize the object. If no constructors are defined for a class, the compiler creates a default constructor that takes no arguments (also called a no-argument constructor). The default constructor for a class calls the default constructor for its superclass (the class it extends), then proceeds to initialize the instance variables in the manner we discussed previously. If the class that this class extends does not have a default constructor, the compiler issues an error message. It is also possible for the programmer to provide a no-argument constructor, as we showed in class Time1 and will see in the next example. If any constructors are defined for a class by the programmer, Java will not create a default constructor for the class. Good Programming Practice 8.4 When appropriate (almost always), provide a constructor to ensure that every object is properly initialized with meaningful values. Common Programming Error 8.6 If constructors are provided for a class, but none of the public constructors are no-argument constructors, and an attempt is made to call a no-argument constructor to initialize an object of the class, a syntax error occurs. A constructor can be called with no arguments only if there are no constructors for the class (the default constructor is called) or if there is a no- argument constructor. 8.7 Using Overloaded Constructors Methods of a class can be overloaded (i.e., several methods in a class may have exactly the same name as defined in Chapter 6, Methods). To overload a method of a class, simply provide a separate method definition with the same name for each version of the method. Remember that overloaded methods must have different parameter lists. Common Programming Error 8.7 Attempting to overload a method of a class with another method that has the exact same signature (name and parameters) is a syntax error. The Time1 constructor in Fig. 8.1 initialized hour, minute and secondto 0 (i.e., 12 midnight in universal time) with a call to the class s setTime method. Figure 8.6 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

Web hosting unlimited bandwidth - 394 Object-Based Programming Chapter 8 1. providing the

Sunday, April 29th, 2007

394 Object-Based Programming Chapter 8 1. providing the -classpath option to the javac compiler, or 2. setting the CLASSPATH environment variable (a special variable that you define and the operating system maintains so that applications can search for classes in the specified locations). In each case, the class path consists of a list of directories and/or archive files separated by semicolons (;). Archive files are individual files that contain directories of other files, typically in compressed format. For example, the standard classes of Java are contained in the archive file rt.jar that is installed with the J2SDK. Archive files normally end with the .jaror .zipfile name extensions. The directories and archive files specified in the class path contain the classes you wish to make available to the Java compiler. For more information on the class path, visit java.sun.com/j2se/1.3/docs/tooldocs/ win32/classpath.html for Windows or java.sun.com/j2se/1.3/docs/ tooldocs/solaris/classpath.html for Solaris/Linux. [Note: We discuss archive files in more detail in Section 8.8.] Common Programming Error 8.5 Specifying an explicit class path eliminates the current directory from the class path. This prevents classes in the current directory from loading properly. If classes must be loaded from the current directory, include the current directory (.) in the explicit class path. Software Engineering Observation 8.13 In general, it is a better practice to use the -classpath option of the compiler, rather than the CLASSPATH environment variable, to specify the class path for a program. This enables each application to have its own class path. Testing and Debugging Tip 8.2 Specifying the class path with the CLASSPATH environment variable can cause subtle and difficult-to-locate errors in programs that use different versions of the same packages. For the example of Fig. 8.4 and Fig. 8.5, we did not specify an explicit class path. Thus, to locate the classes in the com.deitel.jhtp4.ch08 package from this example, the compiler looks in the current directory for the first name in the package com. Next, the compiler navigates the directory structure. Directory comcontains the subdirectory deitel. Directory deitel contains the subdirectory jhtp4. Finally, directory jhtp4 contains subdirectory ch08. In the ch08 directory is the file Time1.class, which is loaded by the compiler to ensure that the class is used properly in our program. Locating the classes to execute the program is similar to locating the classes to compile the program. Like the compiler, the java interpreter searches the standard classes and extension classes first, then searches the class path (the current directory by default). The class path for the interpreter can be specified explicitly by using either of the techniques discussed for the compiler. As with the compiler, it is better to specify an individual program s class path via command-line options to the interpreter. You can specify the class path to the java interpreter via the -classpathor -cpcommand line options followed by a list of directories and/or archive files separated by semicolons (;). 8.6 Initializing Class Objects: Constructors When an object is created, its members can be initialized by a constructor method. A constructor is a method with the same name as the class (including case sensitivity). The pro 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 web application check Vision cheap hosting services

Chapter 8 Object-Based Programming 393 Once the class (Web hosting domain)

Sunday, April 29th, 2007

Chapter 8 Object-Based Programming 393 Once the class is compiled and stored in its package, the class can be imported into programs (Step 4). The TimeTest3application of Fig. 8.5, line 8 specifies that class Time1 should be imported for use in class TimeTest3. At compile time for class TimeTest3, javacmust locate .classfile for Time1, so javac can ensure that class TimeTest3 uses class Time1 correctly. The compiler follows a specific search order to locate the classes it needs. It begins by searching the standard Java classes that are bundled with the J2SDK. Then it searches for extension classes. Java 2 provides an extensions mechanism that enables new packages to be added to Java for development and execution purposes. [Note: The extensions mechanism is beyond the scope of this book. For more information, visit java.sun.com/j2se/1.3/docs/ guide/extensions.] If the class is not found in the standard Java classes or in the extension classes, the complier searches the class path. By default, the class path consists only of the current directory. However, the class path can be modified by: 1 // Fig. 8.5: TimeTest3.java 2 // Class TimeTest3 to use imported class Time1 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 // Deitel packages 8 import com.deitel.jhtp4.ch08.Time1; // import Time1 class 9 10 public class TimeTest3 { 11 12 // create an object of class Time1 and manipulate it 13 public static void main( String args[] ) 14 { 15 Time1 time = new Time1(); // create Time1 object 16 17 time.setTime( 13, 27, 06 ); // set new time 18 String output = 19 “Universal time is: ” + time.toUniversalString() + 20 “nStandard time is: ” + time.toString(); 21 22 JOptionPane.showMessageDialog( null, output, 23 “Packaging Class Time1 for Reuse”, 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 } 28 29 } // end class TimeTest3 Fig. 8.5 Using programmer-defined class Time1in a package. 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 shared web hosting services

392 Object-Based Programming Chapter 8 Software Engineering Observation (Web domain)

Sunday, April 29th, 2007

392 Object-Based Programming Chapter 8 Software Engineering Observation 8.12 A Java source code file has the following order: a package statement (if any), zero or more import statements, then class definitions. Only one of the class definitions in a particular file can be public. Other classes in the file are also placed in the package, but are reusable only from other classes in that package they cannot be imported into classes in another package. They are in the package to support the reusable class in the file. In an effort to provide unique names for every package, Sun Microsystems specifies a convention for package naming that all Java programmers should follow. Every package name should start with your Internet domain name in reverse order. For example, our Internet domain name is deitel.com, so we began our package name with com.deitel. If your domain name is yourcollege.edu, the package name you would use is edu.yourcollege. After the domain name is reversed, you can choose any other names you want for your package. If you are part of a company with many divisions or a university with many schools, you may want to use the name of your division or school as the next name in the package. We chose to use jhtp4 as the next name in our package name to indicate that this class is from Java How to Program: Fourth Edition. The last name in our package name specifies that this package is for Chapter 8 (ch08). [Note: We use our own packages several times throughout the book. You can determine the chapter in which one of our reusable classes is defined by looking at the last part of the package name in the import statement. This appears before the name of the class being imported or before the * if a particular class is not specified.] Step 3 is to compile the class so it is stored in the appropriate package. When a Java file containing a package statement is compiled, the resulting .class file is placed in the directory structure specified by the package statement. The preceding package statement indicates that class Time1 should be placed in the directory ch08. The other names com, deitel and jhtp4 are also directories. The directory names in the package statement specify the exact location of the classes in the package. If these directories do not exist before the class is compiled, the compiler creates them. When compiling a class in a package, there is an extra option (-d) that must be passed to the javaccompiler. This option specifies where to create (or locate) the directories in the package statement. For example, we used the compilation command javac -d . Time1.java to specify that the first directory specified in our package name should be placed in the current directory. The . after -d in the preceding command represents the current directory on the Windows, UNIX and Linux operating systems (and several others as well). After executing the compilation command, the current directory contains a directory called com, com contains a directory called deitel, deitelcontains a directory called jhtp4 and jhtp4 contains a directory called ch08. In the ch08 directory, you can find the file Time1.class. The package directory names become part of the class name when the class is compiled. The class name in this example is actually com.deitel.jhtp4.ch08.Time1 after the class is compiled. You can use this fully qualified name in your programs or you can import the class and use its short name (Time1) in the program. If another package also contains a Time1 class, the fully qualified class names can be used to distinguish between the classes in the program and prevent a naming conflict (also called a name collision). 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 tomcat hosting services

Bulletproof web design - Chapter 8 Object-Based Programming 391 1 // Fig.

Saturday, April 28th, 2007

Chapter 8 Object-Based Programming 391 1 // Fig. 8.4: Time1.java 2 // Time1 class definition in a package 3 package com.deitel.jhtp4.ch08; 4 5 // Java core packages 6 import java.text.DecimalFormat; 7 8 public class Time1 extends Object { 9 private int hour; // 0 - 23 10 private int minute; // 0 - 59 11 private int second; // 0 - 59 12 13 // Time1 constructor initializes each instance variable 14 // to zero. Ensures that each Time1 object starts in a 15 // consistent state. 16 public Time1() 17 { 18 setTime( 0, 0, 0 ); 19 } 20 21 // Set a new time value using universal time. Perform 22 // validity checks on the data. Set invalid values to zero. 23 public void setTime( int h, int m, int s ) 24 { 25 hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 26 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); 27 second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 28 } 29 30 // convert to String in universal-time format 31 public String toUniversalString() 32 { 33 DecimalFormat twoDigits = new DecimalFormat( "00" ); 34 35 return twoDigits.format( hour ) + ":" + 36 twoDigits.format( minute ) + ":" + 37 twoDigits.format( second ); 38 } 39 40 // convert to String in standard-time format 41 public String toString() 42 { 43 DecimalFormat twoDigits = new DecimalFormat( "00" ); 44 45 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + 46 ":" + twoDigits.format( minute ) + 47 ":" + twoDigits.format( second ) + 48 ( hour < 12 ? " AM" : " PM" ); 49 } 50 51 } // end class Time1 Fig. 8.4 Placing Class Time1in a package for reuse. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services

390 Object-Based Programming Chapter 8 Software Engineering Observation (My space web page)

Saturday, April 28th, 2007

390 Object-Based Programming Chapter 8 Software Engineering Observation 8.11 The class designer need not provide set and/or get methods for each private data member; these capabilities should be provided only when it makes sense and after careful thought by the class designer. Testing and Debugging Tip 8.1 Making the instance variables of a class private and the methods of the class public facilitates debugging because problems with data manipulations are localized to the class s methods. 8.5 Creating Packages As we have seen in almost every example in the text, classes and interfaces (discussed in Chapter 9) from preexisting libraries, such as the Java API, can be imported into a Java program. Each class and interface in the Java API belongs to a specific package that contains a group of related classes and interfaces. As applications become more complex, packages help programmers manage the complexity of application components. Packages also facilitate software reuse by enabling programs to import classes from other packages (as we have done in almost every example to this point). Another benefit of packages is that they provide a convention for unique class names. With hundreds of thousands of Java programmers around the world, there is a good chance that the names you choose for classes will conflict with the names that other programmers choose for their classes. This section introduces how to create your own packages and discusses the standard distribution mechanism for packages. The application of Fig. 8.4 and Fig. 8.5 illustrates how to create your own package and use a class from that package in a program. The steps for creating a reusable class are: 1. Define a public class. If the class is not public, it can be used only by other classes in the same package. 2. Choose a package name, and add a package statement to the source code file for the reusable class definition. [Note: There can be only one package statement in a Java source code file.] 3. Compile the class so it is placed in the appropriate package directory structure. 4. Import the reusable class into a program, and use the class. Common Programming Error 8.4 A syntax error occurs if any code appears in a Java file before the package statement (if there is one) in the file. We chose to demonstrate Step 1 by modifying the public class Time1 defined in Fig. 8.1. The new version is shown in Fig. 8.4. No modifications have been made to the implementation of the class, so we will not discuss the implementation details of the class again here. To satisfy Step 2, we added a packagestatement at the beginning of the file. Line 3 uses a packagestatement to define a package named com.deitel.jhtp4.ch08. Placing a packagestatement at the beginning of a Java source file indicates that the class defined in the file is part of the specified package. The only types of statements in Java that can appear outside the braces of a class definition are package statements and import statements. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision web design programs services

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

Saturday, April 28th, 2007

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