You are on page 1of 6

Example: O-O Payroll Program Description of

(§11.4) Problem's Object


Our program
Type
PayrollGenerator
Kind
--
Name
--
Employee sequence Employee [] varying employee
Object-Oriented Design Input file (stream) BufferedReader(
FileReader(
varying empFile
fileName))

Behavior. Our program should read a sequence of Input file name String varying args[0]

employees from an input file, ( managers, secretaries, Employee Employee varying employee[i]

programmers, and consultants). It should compute their Managers Manager varying --

pay and print a paycheck for each employee showing the Secretaries Secretary varying --
Programmers Programmer varying --
employee’s name, ID, and pay.
Consultants Consultant varying --
Pay double varying employee[i].pay( )
Paycheck Paycheck varying paycheck
Employee’s name String varying employee[i].name( )

1 2

OOD Analysis
Kind of employee Common Attributes
Managers, programmers salary Object
Create a SalariedEmployee class
Make Manager and Programmer subclasses.
Payroll Paycheck
Employee
Generator
Secretaries, consultants hourly wage, hours
Create an HourlyEmployee class
Salaried Hourly
Make Secretary and Consultant subclasses. Employee Employee

Salaried employee, hourly employees name, ID number, Manager Programmer Consultant Secretary
pay, etc.
Create an Employee class
Make SalariedEmployee and HourlyEmployee
subclasses.

3 4

1
Operation Responsibility of
Object

i. Read a sequence of employees PayrollGenerator Payroll Employee Paycheck


from a file Generator String name() String name()
main() int id()
(open a stream to a file,
double amount()
readFile() double pay() int id()

read an Employee from a stream, Employee, subclasses


void read(BufferedReader)

close a stream to a file) Salaried


Employee
Hourly
Employee
ii. Compute an employee’s pay Employee double salary() double rate()
double pay()
iii. Construct a paycheck
double hours()
Paycheck void read() double pay()

iv. Access an employee’s name


void read()
Employee
v. Access an employee’s ID number Employee Manager Programmer Consultant Secretary

vi. Access an employee’s pay Employee, subclasses String division()


void read()
String project()
void read()
String worksFor()
void read()

5 6

Because an employee’s pay is computed differently for


File Format salaried and hourly employees, we declare an abstract pay()
method in class Employee so that pay() messages can
Number of employees 7 be sent to an Employee handle.
abstract class Employee extends Object {
Employee #1 kind Manager //--- Employee constructors ---
...
Employee #1 name Grumpy //--- Accessor methods ---
...
Employee #1 id 4 //--- String converter (for output) ---
...
Employee #1 salary 950.00 //--- File input ---
void read(BufferedReader reader) {
Employee #1 division Javadoc try {
myName = reader.readLine();
myID = new Integer(reader.readLine()).intValue();
Employee #2 kind Secretary }
catch (Exception error) {
Employee #2 name Bashful System.err.println("Employee:read(): " + error);
System.exit(1);
Employee #2 id 1 }
Employee #2 wage 8.75 }
//--- Abstract pay method ---
Employee #2 hours 40 abstract public double pay();

Employee #2 works for Grumpy //--- Attribute variables ---


... ... 7
private String myName;
private int myID; 8
}

2
class HourlyEmployee extends Employee {
public final static double OVERTIME_THRESHOLD = 40;
public final static double OVERTIME_FACTOR = 1.5;
But only subclasses SalariedEmployee and
HourlyEmployee will know how to compute their pay, //--- Constructors ---
...
and so we leave it to them to supply a definition for this //--- Accessor methods ---
method: ...
//--- Pay for hourly employee ---
public double pay() {
class SalariedEmployee extends Employee { if (myHours <= OVERTIME_THRESHOLD)
return myHours * myHourlyRate;
//--- Constructors --- else
... return OVERTIME_THRESHOLD * myHourlyRate +
//--- Accessor methods --- (myHours - OVERTIME_THRESHOLD) *
public double pay() { return salary(); } myHourlyRate * OVERTIME_FACTOR;
public double salary() { return mySalary; } }
... ...
//--- String converter (for output) --- //--- String converter (for output) ---
... ...
//--- File input --- //--- File input --- }
... ... pay() is defined differently
//--- Attribute variables --- //--- Attribute variables --- in SalariedEmployee and
private double mySalary; private double myHourlyRate;
} HourlyEmployee.
private double myHours; Polymorphism selects the
}
correct version.
9 10

The Manager class is defined as a subclass of Similarly, the Programmer class is defined as a subclass of
SalariedEmployee. Note that although pay() was an SalariedEmployee:
abstract method in the root class Employee, it was defined
in SalariedEmployee, and it is this definition that is class Programmer extends SalariedEmployee
{
inherited by Manager. //--- Constructors ---
...
class Manager extends SalariedEmployee //--- Accessor method ---
{ public String project() { return myProject; }
//--- Constructors --- ...
... //--- File input ---
//--- Accessor method --- ...
public String division() { return myDivision; }
... //--- Attribute variable ---
//--- String converter (for output) --- private String myProject;
... }
//--- File input ---

//--- Attribute variable --- And Secretary and Consultant classes are defined as
private String myDivision; subclasses of HourlyEmployee and inherit it's methods,
}
including the pay() method.
11 12

3
//--- Accessor methods ---
public String name() { return myName; }
public double amount() { return myAmount; }
The Paycheck class is designed to model paychecks: public int id() { return myID; }

//--- String converter (for output) ---


/** Paycheck.java provides a class to model paychecks. public String toString() {
* New attribute variables store a name, check amount, NumberFormat cf = NumberFormat.getCurrencyInstance();
* and ID number. String formattedAmount = cf.format(myAmount);
* Methods: Constructors: to construct a Paycheck from Employee return myName + "\t\t" + formattedAmount + "\n" + myID;
* accessors; to-string converter for output purposes; }
*/
//--- Attribute variables ---
import java.text.*; // NumberFormat private String myName;
private double myAmount;
class Paycheck extends Object { private int myID;
//--- Paycheck constructor --- }
public Paycheck(Employee employee) {
myName = employee.name();
myAmount = employee.pay(); Note the use of the NumberFormat class method
myID = employee.id(); getCurrencyInstance()to create a number formatter
}
for monetary values; it is then sent the format() message
along with by the amount to be formatted to produce a
String with the appropriate format.
13 14

Finally, there's the PayrollGenerator class that


calculates wages and prepares paychecks: String className = "";
for (;;) {
String blankLine = empFile.readLine(); // eat blank line
class PayrollGenerator { className = empFile.readLine();
public static void main(String [] args) {
Employee [] employee = readFile(args[0]); if (className == null || className == "" // end of stream
|| i == result.length) // end of array
for (int i = 0; i < employee.length; i++) { break;
Paycheck check = new Paycheck(employee[i]);
System.out.println(check + "\n"); result[i] = (Employee)Class.forName(className).newInstance();
} result[i].read(empFile);
i++;
}
public static Employee [] readFile(String fileName) { empFile.close();
BufferedReader empFile = null; }
int numberOfEmployees = 0; catch (Exception e) {
Employee [] result = null; System.err.println(e);
try { System.exit(1);
empFile = new BufferedReader(new FileReader(fileName)); }
return result;
numberOfEmployees = }
new Integer(empFile.readLine()).intValue();
result = new Employee[numberOfEmployees];
int i = 0; 1 2
15 16

4
employees.txt java PayrollGenerator employees.txt
Java has a class named Class that provides various 7 Grumpy $950.00
operations for manipulating classes. Two useful ones are Manager 4
Grumpy
forName() and newInstance(). If String str is 4 Bashful $380.00
the name of a class, 950.00
Java
1

Class.forName(str) Happy $850.00


Secretary 5
returns a Class object with name str; and
!
Bashful
1 Programmer
Doc $318.00
Class.forName(str).newInstance() 8.00 Sneezy
2
45 7
returns an instance of the class with this name, created Happy 850.00
Java Debug
Sneezy $850.00
using the default constructor of that class. It returns that Programmer
7

instance as an Object, and so it must be cast to an Happy Consultant


Dopey
Dopey $20.00
5 3
appropriate type, usually the nearest ancestor. 850.00 3
0.50
For example, Java IDE
40
Sleepy
6
$900.00

(Employee)Class.forName(className).newInstance() Consultant
Doc Programmer
creates an object of type className. 2 Sleepy
6
15.90
17 20 900.00 18
Java Threads

Example: Aviary Program


import java.util.Random;
...
(§11.1) abstract class Bird extends Object {
...
//--- Random number generator ---
/** Static random integer generator
* Receive: int upperBound
Some special features of the bird hierarchy: * Return: a random int from the range 0..upperBound-1
*/
• The root class Bird along with subclasses protected static int randomInt(int upperBound) {
return myRandom.nextInt(upperBound);
WalkingBird and FlyingBird are abstract classes }
with abstract method getCall(). //--- Attribute variables ---
...
• It uses the getClass() method from class Object. private static Random myRandom = new Random();
}
• It has a random number generator used to select a
random phrase by talking parrots and a random number
of "Hoo"s by a snow owl:

19 20

5
/** SnowOwl.java provides a subclass of Owl that models a
* snow owl. It provides a constructor and a definition
* of getCall().
*/

class SnowOwl extends Owl


{
public SnowOwl() { super("white"); }

public String getCall() {


String call = "";
int randomNumber = randomInt(4) + 1; // 1..4

for (int count = 1; count <= randomNumber; count++)


call += "Hoo";

return call + "!";


}
}

21

You might also like