Archive for February, 2009

200 Part III: Working with the Big Picture:

Saturday, February 28th, 2009

200 Part III: Working with the Big Picture: Object-Oriented Programming Well, you can dig right into the PartTimeEmployeeclass code, make a few changes, and hope for the best. (Not a good idea!) You can follow the previous section s advice and create a subclass of the existing PartTimeEmployeeclass. But wait, you say. The existing PartTimeEmployeeclass already has a findPaymentAmountmethod. Do I need some tricky way of bypassing this existing findPaymentAmountmethod for each double-pay-for-overtime employee? At this point, you can thank your lucky stars that you re doing object- oriented programming in Java. With object-oriented programming, you can create a subclass that overrides the functionality of its parent class. Listing 8-8 has just such a subclass. Listing 8-8: Yet Another Subclass class PartTimeWithOver extends PartTimeEmployee { public double findPaymentAmount(int hours) { if(hours <= 40) { return getHourlyRate() * hours; } else { return getHourlyRate() * 40 + getHourlyRate() * 2 * (hours 40); } } } Figure 8-10 shows the relationship between the code in Listing 8-8 and other pieces of code in this chapter. In particular, PartTimeWithOveris a subclass of a subclass. In object-oriented programming, a chain of this kind is not the least bit unusual. In fact, as subclasses go, this chain is rather short. The PartTimeWithOverclass extends the PartTimeEmployeeclass, but PartTimeWithOverpicks and chooses what it wants to inherit from the PartTimeEmployeeclass. Because PartTimeWithOverhas its own declaration for the findPaymentAmountmethod, the PartTimeWithOverclass does- n t inherit a findPaymentAmountmethod from its parent. (See Figure 8-11.)

If you looking for unlimited one inclusive web hosting plan please check unlimited web hosting website.

Chapter 8: Saving Time and Money: Reusing Existing

Saturday, February 28th, 2009

Chapter 8: Saving Time and Money: Reusing Existing Code 199 Figure 8-9: Paying your employees. Compared with its full-time cousin, the payOnePTEmployeemethod pulls one extra idea out of its bag of tricks. When the time comes to get the number of hours the employee worked, the payOnePTEmployeemethod doesn t consult a disk file. Instead, the method asks the user for live keyboard input. The thought here is that the disk file is where all the long-term information about employees lives. Because the number of hours an employee worked this week isn t long-term information, the payOnePTEmployeemethod gets the user to enter this information on the fly. The payOnePTEmployeemethod reads a name, a job title, and an hourly rate from the disk file. Then the method reads a number of hours from the keyboard. Because the payOnePTEmployeemethod reads data from two different sources, you pass two different scanners to the method. In the method s parameter list, you separate the two items with a comma. Overriding Existing Methods (Changing the Payments for Some of Your Employees) Wouldn t you know it! Some knucklehead in the human resources department offered double pay for overtime to one of your part-time employees. Now word is getting around, and some of the other part-timers want double pay for their overtime work. If this keeps up, you ll end up in the poorhouse, so you need to send out a memo to all the part-time employees, explaining why earning more money is not to their benefit. In the meantime, you have two kinds of part-time employees the ones who receive double pay for overtime hours and the ones who don t so you need to modify your payroll software. What are your options?

For high quality java hosting services please check tomcat web hosting website.

198 Part III: Working with the Big Picture:

Saturday, February 28th, 2009

198 Part III: Working with the Big Picture: Object-Oriented Programming Listing 8-7 (continued) employee.setHourlyRate(diskScanner.nextDouble()); diskScanner.nextLine(); diskScanner.nextLine(); //Reads the dashed line that // separates two employees out.print( Enter ); out.print(employee.getName()); out.print( s hours worked this week: ); int hours = kbdScanner.nextInt(); employee.cutCheck(employee.findPaymentAmount(hours)); out.println(); } } For all its complexity, the code in Listing 8-7 still isn t a full-blown payroll program. It s a toy program, but it s a bit more realistic than the program in Listing 8-6. The code in Listing 8-7 writes checks for six employees three full-time employees and three part-time employees. Calls to payOneFTEmployeeand payOnePTEmployeemake sure that each employee receives a check. Each of these payOneEmployeemethods reads data from a file and uses the data to fill the employeeobject s variables with values. Figure 8-8 shows the file that I used to test Listing 8-7, and the resulting run is shown in Figure 8-9. Figure 8-8: Input for the big-time payroll program.

For high quality java hosting services please check java web hosting website.

Chapter 8: Saving Time and Money: Reusing Existing

Saturday, February 28th, 2009

Chapter 8: Saving Time and Money: Reusing Existing Code 197 Listing 8-7: Big-Time Payroll Program import static java.lang.System.out; import java.util.Scanner; import java.io.File; import java.io.IOException; class DoPayrollTypeP { public static void main(String args[]) throws IOException { Scanner diskScanner = new Scanner(new File( EmpInfoNew.txt )); Scanner kbdScanner = new Scanner(System.in); for (int empNum = 1; empNum <= 3; empNum++) { payOneFTEmployee(diskScanner); } for (int empNum = 4; empNum <= 6; empNum++) { payOnePTEmployee(diskScanner, kbdScanner); } } public static void payOneFTEmployee(Scanner diskScanner) { FullTimeEmployee employee = new FullTimeEmployee(); employee.setName(diskScanner.nextLine()); employee.setJobTitle(diskScanner.nextLine()); employee.setWeeklySalary(diskScanner.nextDouble()); employee.setBenefitDeduction(diskScanner.nextDouble()); diskScanner.nextLine(); diskScanner.nextLine(); //Reads the dashed line that // separates two employees employee.cutCheck(employee.findPaymentAmount()); out.println(); } public static void payOnePTEmployee (Scanner diskScanner, Scanner kbdScanner) { PartTimeEmployee employee = new PartTimeEmployee(); employee.setName(diskScanner.nextLine()); employee.setJobTitle(diskScanner.nextLine()); (continued)

For high quality website hosting services please check cheap web hosting website.

196 Part III: Working with the Big Picture:

Friday, February 27th, 2009

196 Part III: Working with the Big Picture: Object-Oriented Programming Always feed a method the value types that it wants in its parameter list. The second half of the story In the second half of Listing 8-6, the code creates an object of type PartTimeEmployee. A variable of type PartTimeEmployeecan do some of the same things a FullTimeEmployeevariable can do. But the PartTimeEmployeeclass doesn t have the setWeeklySalaryand setBenefitDeductionmethods. Instead, the PartTimeEmployeeclass has the setHourlyRatemethod. (See Listing 8-5.) So, in Listing 8-6, the nextto- last line is a call to the setHourlyRatemethod. The last line of Listing 8-6 is by far the most interesting. On that line, the code hands the number 10(the number of hours worked) to the findPayment Amountmethod. Compare this with the earlier call to findPaymentAmount the call for the full-time employee in the first half of Listing 8-6. Between the two subclasses, FullTimeEmployeeand PartTimeEmployee, are two different findPaymentAmountmethods. The two methods have two different kinds of parameter lists: The FullTimeEmployeeclass s findPaymentAmountmethod takes no parameters (Listing 8-3). The PartTimeEmployeeclass s findPaymentAmountmethod takes one intparameter (Listing 8-5). This is par for the course. Finding the payment amount for a part-time employee isn t the same as finding the payment amount for a full-time employee. A part- time employee s pay changes each week, depending on the number of hours the employee works in a week. The full-time employee s pay stays the same each week. So the FullTimeEmployeeand PartTimeEmployeeclasses both have findPaymentAmountmethods, but each class s method works quite differently. A program for the maximalist If you crave useful results and practical applications, you either skipped over the last listing or gritted your teeth while you read through it. Listing 8-7 gives you the same information with a more practical point of view. Of course, there s a price. Listing 8-7 is longer and more complicated than the listing in the previous section. Oh, well!

If you looking for unlimited one inclusive web hosting plan please check web hosting plan website.

Chapter 8: Saving Time and Money: Reusing Existing

Friday, February 27th, 2009

Chapter 8: Saving Time and Money: Reusing Existing Code 195 To understand Listing 8-6, you need to keep an eye on three classes: Employee, FullTimeEmployee, and PartTimeEmployee. (For a look at the code that defines these classes, see Listings 8-1, 8-3, and 8-5.) The first half of Listing 8-6 deals with a full-time employee. Notice how so many methods are available for use with the ftEmployeevariable. For instance, you can call ftEmployee.setWeeklySalarybecause ftEmployeehas type FullTimeEmployee. You can also call ftEmployee.setNamebecause the FullTimeEmployeeclass extends the Employeeclass. Because cutCheckis declared in the Employeeclass, you can call ftEmployee.cutCheck. But you can also call ftEmployee.findPayment Amountbecause a findPaymentAmountmethod is in the FullTimeEmployee class. Making types match Look again at the first half of Listing 8-6. Take special notice of that last statement the one in which the full-time employee is actually cut a check. The statement forms a nice, long chain of values and their types. You can see this by reading the statement from the inside out. Method ftEmployee.findPaymentAmountis called with an empty parameter list (Listing 8-6). That s good, because the findPaymentAmountmethod takes no parameters (Listing 8-3). The findPaymentAmountmethod returns a value of type double (again, Listing 8-3). The doublevalue that ftEmployee.findPaymentAmountreturns is passed to method ftEmployee.cutCheck(Listing 8-6). That s good, because the cutCheckmethod takes one parameter of type double (Listing 8-1). For a fanciful graphic illustration, see Figure 8-7. findPaymentAmount cutCheck Figure 8-7: No parameters double Matching parameters. No parameters double

For high quality java hosting services please check tomcat web hosting website.

194 Part III: Working with the Big Picture:

Friday, February 27th, 2009

194 Part III: Working with the Big Picture: Object-Oriented Programming A program for the minimalist Listing 8-6 shows you a bare-bones program that uses the subclasses FullTimeEmployeeand PartTimeEmployee. Figure 8-6 shows the program s output. Listing 8-6: Use Subclasses and Then Leave Me Alone class DoPayrollTypeF { public static void main(String args[]) { FullTimeEmployee ftEmployee = new FullTimeEmployee(); ftEmployee.setName( Barry Burd ); ftEmployee.setJobTitle( CEO ); ftEmployee.setWeeklySalary(5000.00); ftEmployee.setBenefitDeduction(500.00); ftEmployee.cutCheck(ftEmployee.findPaymentAmount()); System.out.println(); PartTimeEmployee ptEmployee = new PartTimeEmployee(); ptEmployee.setName( Steve Surace ); ptEmployee.setJobTitle( Driver ); ptEmployee.setHourlyRate(7.53); ptEmployee.cutCheck(ptEmployee.findPaymentAmount(10)); } } Figure 8-6: The output of the program in Listing 8-6.

For high quality website hosting services please check cheap web hosting website.

Chapter 8: Saving Time and Money: Reusing Existing

Thursday, February 26th, 2009

Chapter 8: Saving Time and Money: Reusing Existing Code 193 } public double findPaymentAmount(int hours) { return hourlyRate * hours; } } Unlike the FullTimeEmployeeclass, PartTimeEmployeehas no salary or deduction. Instead PartTimeEmployeehas an hourlyRatevariable. (Adding a numberOfHoursWorkedvariable would also be a possibility. I chose not to do this, figuring that the number of hours a part-time employee works will change drastically from week to week.) Using Subclasses The previous section tells a story about creating subclasses. It s a good story, but it s incomplete. Creating subclasses is fine, but you gain nothing from these subclasses unless you write code to use them. So in this section, you explore code that uses subclasses. Now the time has come for you to classify yourself as either a type-F person or a type-P person. A type-F person wants to see the fundamentals. (The letter F stands for fundamentals.) Show me a program that lays out the principles in their barest, most basic form, says the type-F person. A type-F person isn t worried about bells and whistles. The bells come later, and the whistles may never come at all. If you re a type-F person, you want to see a program that uses subclasses and then moves out of your way so you can get some work done. On the other hand, a type-P person wants practical applications. (The letter P stands for practical.) Type-P people need to see ideas in context; otherwise the ideas float away too quickly. Show me a program that demonstrates the usefulness of subclasses, says the type-P person. I have no use for your stinking abstractions. I want real-life examples, and I want them now! Because I m always aiming to please my reader, this section has two (count em two) examples that make use of the previous section s subclasses. Listing 8-6, which is for the type-F crowd, is lean and simple and makes good bedtime reading. On the other hand, Listing 8-7, which is for type-P fanatics, shows how subclasses fit into a useful context. So that s it. Choose your poison and read on.

For reliable and cheap web hosting services please check cheap web hosting website.

192 Part III: Working with the Big Picture:

Thursday, February 26th, 2009

192 Part III: Working with the Big Picture: Object-Oriented Programming Listing 8-4 (continued) return benefitDeduction; } public double findPaymentAmount() { return weeklySalary - benefitDeduction; } public void cutCheck(double amountPaid) { out.printf( Pay to the order of %s , name); out.printf( (%s) ***$ , jobTitle); out.printf( %,.2fn , amountPaid); } } Why does the title for Listing 8-4 call that code fake? (Should the code feel insulted?) Well, the main difference between Listing 8-4 and the inheritance situation in Listings 8-1 and 8-3 is this: A child class can t directly reference the private variables of its parent class. To do anything with the parent class s private variables, the child class has to call the parent class s accessor methods. Back in Listing 8-3, calling setName( Rufus )would be legal, but the code name= Rufus wouldn t be. If you believe everything you read in Listing 8-4, you think that code in the FullTimeEmployeeclass can do name= Rufus . Well, it can t. (My, what a subtle point this is!) You don t need the Employee.javafile on your hard drive to write code that extends the Employeeclass. All you need is the file Employee.class. Creating subclasses is habit-forming After you re accustomed to extending classes, you can get extend-happy. If you created a FullTimeEmployeeclass, you might as well create a PartTimeEmployeeclass, as shown in Listing 8-5. Listing 8-5: What Is a PartTimeEmployee? class PartTimeEmployee extends Employee { private double hourlyRate; public void setHourlyRate(double rateIn) { hourlyRate = rateIn; } public double getHourlyRate() { return hourlyRate;

For reliable and cheap web hosting services please check javaweb hosting website.

Chapter 8: Saving Time and Money: Reusing Existing

Thursday, February 26th, 2009

Chapter 8: Saving Time and Money: Reusing Existing Code 191 setJobTitle, getJobTitle, and cutCheck. The FullTimeEmployeeclass is a subclass of the Employeeclass. That means the Employeeclass is the superclass of the FullTimeEmployeeclass. You can also talk in terms of blood relatives. The FullTimeEmployeeclass is the child of the Employee class, and the Employeeclass is the parent of the FullTimeEmployeeclass. It s almost (but not quite) as if the FullTimeEmployeeclass were defined by the code in Listing 8-4. Listing 8-4: Fake (But Informative) Code import static java.lang.System.out; class FullTimeEmployee { private String name; private String jobTitle; private double weeklySalary; private double benefitDeduction; public void setName(String nameIn) { name = nameIn; } public String getName() { return name; } public void setJobTitle(String jobTitleIn) { jobTitle = jobTitleIn; } public String getJobTitle() { return jobTitle; } public void setWeeklySalary(double weeklySalaryIn) { weeklySalary = weeklySalaryIn; } public double getWeeklySalary() { return weeklySalary; } public void setBenefitDeduction(double benefitDedIn) { benefitDeduction = benefitDedIn; } public double getBenefitDeduction() { (continued)

For high quality website hosting services please check java web hosting website.