26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

482 Object-Oriented <strong>Program</strong>ming Chapter 9<br />

16<br />

17 // set PieceWorker's wage<br />

18 public void setWage( double wage )<br />

19 {<br />

20 wagePerPiece = ( wage > 0 ? wage : 0 );<br />

21 }<br />

22<br />

23 // set number of items output<br />

24 public void setQuantity( int numberOfItems )<br />

25 {<br />

26 quantity = ( numberOfItems > 0 ? numberOfItems : 0 );<br />

27 }<br />

28<br />

29 // determine PieceWorker's earnings<br />

30 public double earnings()<br />

31 {<br />

32 return quantity * wagePerPiece;<br />

33 }<br />

34<br />

35 public String <strong>to</strong>String()<br />

36 {<br />

37 return "Piece worker: " + super.<strong>to</strong>String();<br />

38 }<br />

39<br />

40 } // end class PieceWorker<br />

Fig. Fig. 9.19 9.19 PieceWorker extends abstract class Employee (part 2 of 2).<br />

Class HourlyWorker (Fig. 9.20) is derived from Employee. The public<br />

methods include a construc<strong>to</strong>r that takes a first name, a last name, a wage and the number<br />

of hours worked as arguments and passes the first name and last name <strong>to</strong> the Employee<br />

construc<strong>to</strong>r; set methods <strong>to</strong> assign new values <strong>to</strong> instance variables wage and hours; an<br />

earnings method defining how <strong>to</strong> calculate an HourlyWorker’s earnings; and a<br />

<strong>to</strong>String method that forms a String containing the type of the employee (i.e.,<br />

"Hourly worker: ") followed by the hourly worker’s name.<br />

1 // Fig. 9.20: HourlyWorker.java<br />

2 // Definition of class HourlyWorker<br />

3<br />

4 public final class HourlyWorker extends Employee {<br />

5 private double wage; // wage per hour<br />

6 private double hours; // hours worked for week<br />

7<br />

8 // construc<strong>to</strong>r for class HourlyWorker<br />

9 public HourlyWorker( String first, String last,<br />

10 double wagePerHour, double hoursWorked )<br />

11 {<br />

12 super( first, last ); // call superclass construc<strong>to</strong>r<br />

13 setWage( wagePerHour );<br />

14 setHours( hoursWorked );<br />

15 }<br />

Fig. Fig. 9.20 9.20 HourlyWorker extends abstract class Employee (part 1 of 2).<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!