Archive for July, 2007

418 Object-Based Programming Chapter 8 1 // Fig. (Web hosting faq)

Tuesday, July 31st, 2007

418 Object-Based Programming Chapter 8 1 // Fig. 8.16: PackageDataTest.java 2 // Classes in the same package (i.e., the same directory) can 3 // use package access data of other classes in the same package. 4 5 // Java extension packages 6 import javax.swing.JOptionPane; 7 8 public class PackageDataTest { 9 10 // Java extension packages 11 public static void main( String args[] ) 12 { 13 PackageData packageData = new PackageData(); 14 15 // append String representation of packageData to output 16 String output = 17 “After instantiation:n” + packageData.toString(); 18 19 // change package access data in packageData object 20 packageData.number = 77; 21 packageData.string = “Good bye”; 22 23 // append String representation of packageData to output 24 output += “nAfter changing values:n” + 25 packageData.toString(); 26 27 JOptionPane.showMessageDialog( null, output, 28 “Demonstrating Package Access”, 29 JOptionPane.INFORMATION_MESSAGE ); 30 31 System.exit( 0 ); 32 } 33 34 } // end class PackageDataTest 35 36 // class with package access instance variables 37 class PackageData { 38 int number; // package access instance variable 39 String string; // package access instance variable 40 41 // constructor 42 public PackageData() 43 { 44 number = 0; 45 string = “Hello”; 46 } 47 48 // convert PackageData object to String representation 49 public String toString() 50 { 51 return “number: ” + number + ” string: ” + string; 52 } 53 Fig. 8.16 Package access to members of a class (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 (Make my own web site) Object-Based Programming 417 18 JOptionPane.showMessageDialog( null,

Tuesday, July 31st, 2007

Chapter 8 Object-Based Programming 417 18 JOptionPane.showMessageDialog( null, 19 employee.toString(), “Testing Class Employee”, 20 JOptionPane.INFORMATION_MESSAGE ); 21 22 System.exit( 0 ); 23 } 24 25 } // end class EmployeeTest Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Fig. 8.15 Demonstrating an object with a member object reference (part 2 of 2). 8.12 Package Access When no member access modifier is provided for a method or variable when it is defined in a class, the method or variable is considered to have package access. If your program consists of one class definition, this has no specific effects on the program. However, if your program uses multiple classes from the same package (i.e., a group of related classes), these classes can access each other s package-access methods and data directly through a reference to an object. Performance Tip 8.3 Package access enables objects of different classes to interact without the need for set and get methods that provide access to data, thus eliminating some of the method call overhead. Let us consider a mechanical example of package access. The application of Fig. 8.16 contains two classes the PackageDataTest application class (lines 8 34) and the PackageData class (lines 37 54). In the PackageData class definition, lines 38 39 declare the instance variables number and string with no member access modifiers; therefore, these are package access instance variables. The PackageDataTestapplication s main method creates an instance of the PackageData class (line 13) to demonstrate the ability to modify the PackageData instance variables directly (as shown on lines 20 21). The results of the modification can be seen in the output window. When you compile this program, the compiler produces two separate files a .class file for class PackageData and a .class file for class PackageDataTest. Every Java class has its own .classfile. These two .classfiles are placed in the same directory by the compiler automatically and are considered to be part of the same package (they are certainly related by the fact that they are in the same file). Because they are part of the same package, class PackageDataTest is allowed to modify the package access data of objects of class PackageData. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

416 Object-Based Programming Chapter 8 1 (Photography web hosting) // Fig.

Monday, July 30th, 2007

416 Object-Based Programming Chapter 8 1 // Fig. 8.14: Employee.java 2 // Definition of class Employee. 3 package com.deitel.jhtp4.ch08; 4 5 public class Employee extends Object { 6 private String firstName; 7 private String lastName; 8 private Date birthDate; 9 private Date hireDate; 10 11 // constructor to initialize name, birth date and hire date 12 public Employee( String first, String last, 13 int birthMonth, int birthDay, int birthYear, 14 int hireMonth, int hireDay, int hireYear ) 15 { 16 firstName = first; 17 lastName = last; 18 birthDate = new Date( birthMonth, birthDay, birthYear ); 19 hireDate = new Date( hireMonth, hireDay, hireYear ); 20 } 21 22 // convert Employee to String format 23 public String toString() 24 { 25 return lastName + “, ” + firstName + 26 ” Hired: ” + hireDate.toString() + 27 ” Birthday: ” + birthDate.toString(); 28 } 29 30 } // end class Employee Fig. 8.14 Employeeclass with member object references. 1 // Fig. 8.15: EmployeeTest.java 2 // Demonstrating an object with a member object. 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 // Deitel packages 8 import com.deitel.jhtp4.ch08.Employee; 9 10 public class EmployeeTest { 11 12 // test class Employee 13 public static void main( String args[] ) 14 { 15 Employee employee = new Employee( “Bob”, “Jones”, 16 7, 24, 49, 3, 12, 88 ); 17 Fig. 8.15 Demonstrating an object with a member object reference (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based Programming 415 7 private int (Web hosting services)

Monday, July 30th, 2007

Chapter 8 Object-Based Programming 415 7 private int day; // 1-31 based on month 8 private int year; // any year 9 10 // Constructor: Confirm proper value for month; 11 // call method checkDay to confirm proper 12 // value for day. 13 public Date( int theMonth, int theDay, int theYear ) 14 { 15 if ( theMonth > 0 && theMonth <= 12 ) // validate month 16 month = theMonth; 17 else { 18 month = 1; 19 System.out.println( "Month " + theMonth + 20 " invalid. Set to month 1." ); 21 } 22 23 year = theYear; // could validate year 24 day = checkDay( theDay ); // validate day 25 26 System.out.println( 27 "Date object constructor for date " + toString() ); 28 } 29 30 // Utility method to confirm proper day value 31 // based on month and year. 32 private int checkDay( int testDay ) 33 { 34 int daysPerMonth[] = 35 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 36 37 // check if day in range for month 38 if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) 39 return testDay; 40 41 // check for leap year 42 if ( month == 2 && testDay == 29 && 43 ( year % 400 == 0 || 44 ( year % 4 == 0 && year % 100 !=0 ) ) ) 45 return testDay; 46 47 System.out.println( “Day ” + testDay + 48 ” invalid. Set to day 1.” ); 49 50 return 1; // leave object in consistent state 51 } 52 53 // Create a String of the form month/day/year 54 public String toString() 55 { 56 return month + “/” + day + “/” + year; 57 } 58 59 } // end class Date Fig. 8.13 Dateclass (part 2 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

414 Object-Based Programming Chapter 8 8.11 Composition: Objects (Make a web site)

Sunday, July 29th, 2007

414 Object-Based Programming Chapter 8 8.11 Composition: Objects as Instance Variables of OtherClasses An AlarmClock class object needs to know when it is supposed to sound its alarm, so why not include a reference to a Time object as a member of the AlarmClock object? Such a capability is called composition. A class can have references to objects of other classes as members. Software Engineering Observation 8.18 One form of software reuse is composition, in which a class has references to objects of other classes as members. The next program contains three classes Date(Fig. 8.13), Employee(Fig. 8.14) and EmployeeTest (Fig. 8.15). Class Employee contains instance variables firstName, lastName, birthDateand hireDate. Members birthDateand hireDateare references to Dates that contain instance variables month, dayand year. This demonstrates that a class can contain references to objects of other classes. Class EmployeeTestinstantiates an Employeeand initializes and displays its instance variables. The Employeeconstructor (Fig. 8.14, lines 12 20) takes eight arguments first, last, birthMonth, birthDay, birthYear, hireMonth, hireDayand hireYear. Arguments birth- Month, birthDayand birthYearare passed to the Dateconstructor (Fig. 8.13, lines 13 28) to initialize the birthDate object and hireMonth, hireDay and hireYear are passed to the Dateconstructor to initialize the hireDateobject. A member object does not need to be initialized immediately with constructor arguments. If an empty argument list is provided when a member object is created, the object s default constructor (or no-argument constructor if one is available) will be called automatically. Values, if any, established by the default constructor (or no-argument constructor) can then be replaced by set methods. Performance Tip 8.2 Initialize member objects explicitly at construction time by passing appropriate arguments to the constructors of the member objects. This eliminates the overhead of initializing member objects twice once when the member object s default constructor is called and again when set methods are used to provide initial values for the member object. Note that both class Date(Fig. 8.13) and class Employee(Fig. 8.14) are defined as part of the package com.deitel.jhtp4.ch08 as specified on line 3 of each file. Because they are in the same package (i.e., the same directory), class Employeedoes not need to import class Dateto use it. When the compiler searches for the file Date.class, the compiler knows to search the directory where Employee.class is located. Classes in a package never need to import other classes from the same package. 1 // Fig. 8.13: Date.java 2 // Declaration of the Date class. 3 package com.deitel.jhtp4.ch08; 5 public class Date extends Object { 6 private int month; // 1-12 Fig. 8.13 Dateclass (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based (Medical web site) Programming 413 8 // Java

Sunday, July 29th, 2007

Chapter 8 Object-Based Programming 413 8 // Java extension packages 9 import javax.swing.*; 10 11 public class Increment extends JApplet 12 implements ActionListener { 13 14 private int count = 0, total = 0; 15 private final int INCREMENT = 5; // constant variable 16 17 private JButton button; 18 19 // set up GUI 20 public void init() 21 { 22 Container container = getContentPane(); 23 24 button = new JButton( “Click to increment” ); 25 button.addActionListener( this ); 26 container.add( button ); 27 } 28 29 // add INCREMENT to total when user clicks button 30 public void actionPerformed( ActionEvent actionEvent ) 31 { 32 total += INCREMENT; 33 count++; 34 showStatus( “After increment ” + count + 35 “: total = ” + total ); 36 } 37 38 } // end class Increment Fig. 8.11Initializing a finalvariable (part 2 of 2). Fig. 8.11 Figure 8.12 illustrates compiler errors produced for the program of Fig. 8.11 if instance variable INCREMENTis declared final, but is not initialized in the declaration. Increment.java:11: variable INCREMENT might not have been initialized public class Increment extends JApplet ^ 1 error Fig. 8.1212 Compiler error message as a result of not initializing increment. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

412 Object-Based Programming Chapter 8 available and how (Web hosting resellers)

Saturday, July 28th, 2007

412 Object-Based Programming Chapter 8 available and how closely they meet software developer requirements, and the like. Many interesting research and development problems have been solved and many more need to be solved; these problems will be solved because the potential value of software reuse is enormous. 8.10 Final Instance Variables We have emphasized repeatedly the principle of least privilege as one of the most fundamental principles of good software engineering. Let us see one way in which this principle applies to instance variables. Some instance variables need to be modifiable and some do not. The programmer can use the keyword finalto specify that a variable is not modifiable and that any attempt to modify the variable is an error. For example, private final int INCREMENT = 5; declares a constant instance variable INCREMENTof type intand initializes it to 5. Software Engineering Observation 8.17 Declaring an instance variable as final helps enforce the principle of least privilege. If an instance variable should not be modified, declare it to be final to expressly forbid modification. Testing and Debugging Tip 8.3 Accidental attempts to modify a final instance variable are caught at compile time rather than causing execution-time errors. It is always preferable to get bugs out at compile time, if possible, rather than allowing them to slip through to execution time (where studies have found that the cost of repair is often as much as ten times more expensive). Common Programming Error 8.9 Attempting to modify a final instance variable after it is initialized is a syntax error. The applet of Fig. 8.11 creates a final instance variable INCREMENT of type int and initializes it to 5 in its declaration (line 15). A finalvariable cannot be modified by assignment after it is initialized. Such a variable can be initialized in its declaration or in every constructor of the class. Common Programming Error 8.10 Not initializing a final instance variable in its declaration or in every constructor of the class is a syntax error. 1 // Fig. 8.11: Increment.java 2 // Initializing a final variable 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 Fig. 8.11Initializing a finalvariable (part 1 of 2). Fig. 8.11 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Anonymous web server - Chapter 8 Object-Based Programming 411 8.9 Software Reusability

Saturday, July 28th, 2007

Chapter 8 Object-Based Programming 411 8.9 Software Reusability Java programmers concentrate on crafting new classes and reusing existing classes. Many class libraries exist, and others are being developed worldwide. Software is then constructed from existing, well-defined, carefully tested, well-documented, portable, widely available components. This kind of software reusability speeds the development of powerful, high-quality software. Rapid applications development (RAD) is of great interest today. Java programmers now have thousands of classes in the Java API from which to choose to help them implement Java programs. Indeed, Java is not just a programming language. It is a framework in which Java developers can work to achieve true reusability and rapid applications development. Java programmers can focus on the task at hand when developing their programs and leave the lower-level details to the classes of the Java API. For example, to write a program that draws graphics, a Java programmer does not require knowledge of graphics on every computer platform where the program will execute. Instead, a Java programmer concentrates on learning Java s graphics capabilities (which are quite substantial and growing) and writes a Java program that draws the graphics, using Java s API classes such as Graphics. When the program executes on a given computer, it is the job of the interpreter to translate Java commands into commands that the local computer can understand. The Java API classes enable Java programmers to bring new applications to market faster by using preexisting, tested components. Not only does this reduce development time, it also improves programmers ability to debug and maintain applications. To take advantage of Java s many capabilities, it is essential that programmers take the time to familiarize themselves with the variety of packages and classes in the Java API. There are many Web-based resources at java.sun.com to help you with this task. The primary resource for learning about the Java API is the Java API documentation, which can be found at java.sun.com/j2se/1.3/docs/api/index.html In addition, java.sun.com provides many other resources, including tutorials, articles and sites specific to individual Java topics. Java developers should also register (for free) at the Java Developer Connection developer.java.sun.com This site provides additional resources that Java developers will find useful, including more tutorials and articles, and links to other Java resources. See Appendix B for a more complete list of Java-related Internet and World Wide Web resources. Good Programming Practice 8.6 Avoid reinventing the wheel. Study the capabilities of the Java API. If the API already contains a class that meets the requirements of your program, use that class rather than creating your own. In general, to realize the full potential of software reusability, we need to improve cataloging schemes, licensing schemes, protection mechanisms that ensure master copies of classes are not corrupted, description schemes that system designers use to determine if existing objects meet their needs, browsing mechanisms that determine what classes are Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

410 Object-Based Programming Chapter 8 ual (Web hosting comparison) file.] It

Saturday, July 28th, 2007

410 Object-Based Programming Chapter 8 ual file.] It is important that the directory structure in the JAR file match the directory structure for the packaged classes. Therefore, we executed the jarcommand from the directory in which com is located. To confirm that the files were archived directly, you can issue the command jar tvf TimeTest5.jar which produces the listing in Fig. 8.10. In the preceding command, the options for the jar utility are tvf. The letter t indicates that the table of contents for the JAR should be listed. The letter v indicates that the output should be verbose (the verbose output includes the file size in bytes and the date and time each file was created, in addition to the directory structure and file name). The letter f specifies that the next argument on the command line is the JAR file to use. The only remaining issue is to specify the archive as part of the applet s HTML file. In prior examples, tags had the form To specify that the applet classes are located in a JAR file, use an tag of the form: The archive attribute can specify a comma-separated list of archive files for use in an applet. Each file in the archivelist will be downloaded by the browser when it encounters the tags in the HTML document. For the TimeTest5 applet, the applet tag would be Try loading this applet into your Web browser. Remember that you must either have a browser that supports Java 2 (such as Netscape Navigator 6) or convert the HTML file for use with the Java Plug-in (as discussed in Chapter 3). 0 Fri May 25 14:13:14 EDT 2001 META-INF/ 71 Fri May 25 14:13:14 EDT 2001 META-INF/MANIFEST.MF 2959 Fri May 25 13:42:32 EDT 2001 TimeTest5.class 0 Fri May 18 17:35:18 EDT 2001 com/deitel/ 0 Fri May 18 17:35:18 EDT 2001 com/deitel/jhtp4/ 0 Fri May 18 17:35:18 EDT 2001 com/deitel/jhtp4/ch08/ 1765 Fri May 18 17:35:18 EDT 2001 com/deitel/jhtp4/ch08/Time3.class Fig. 8.10 Contents of TimeTest5.jar. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based Programming (Web site domain) 409 Set methods are

Friday, July 27th, 2007

Chapter 8 Object-Based Programming 409 Set methods are certainly important from a software engineering standpoint, because they can perform validity checking. Set and get methods have another important software engineering advantage, discussed in the following Software Engineering Observation. Software Engineering Observation 8.16 Accessing private data through set and get methods not only protects the instance variables from receiving invalid values, but also insulates clients of the class from the representation of the instance variables. Thus, if the representation of the data changes (typically, to reduce the amount of storage required, improve performance or enhance the class in other ways), only the method implementations need to change the clients need not change as long as the interface provided by the methods remains the same. 8.8.1 Executing an Applet that Uses Programmer-Defined Packages After compiling the classes in Fig. 8.8 and Fig. 8.9, you can execute the applet from a command window with the command appletviewer TimeTest5.html As we discussed when we introduced packages earlier in this chapter, the interpreter can locate packaged classes in the current directory. The appletviewer is a Java application that executes a Java applet. Like the interpreter, the appletviewer can load standard Java classes and extension classes installed on the local computer. However, the applet- viewer does not use the class path to locate classes in programmer-defined packages. For an applet, such classes should be bundled with the applet class in an archive file called a Java Archive (JAR) file. Remember that applets normally are downloaded from the Internet into a Web browser (see Chapter 3 for more information). Bundling the classes and packages that compose an applet enables the applet and its supporting classes to be downloaded as a unit, then executed in the browser (or via the Java Plug-in for browsers that do not support Java 2). To bundle the classes in Fig. 8.8 and Fig. 8.9, open a command window and change directories to the location in which TimeTest5.class is stored. In that same directory should be the com directory that begins the package directory structure for class Time3. In that directory, issue the following command jar cf TimeTest5.jar TimeTest5.class com*.* to create the JAR file. [Note: This command uses as the directory separator from the MSDOS prompt. UNIX would use / as the directory separator.] In the preceding command, jar is the Java archive utility used to create JAR files. Next are the options for the jar utility cf. The letter c indicates that we are creating a JAR file. The letter f indicates that the next argument in the command line (TimeTest5.jar) is the name of the JAR file to create. Following the options and JAR file name are the actual files that will be included in the JAR file. We specified TimeTest5.class and com*.*, indicating that TimeTest5.class and all the files in the com directory should be included in the JAR file. The com directory begins the package that contains the .class file for the Time3. [Note: You can include selected files by specifying the path and file name for each individ Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01