











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












Today we’ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll. Object-oriented programming requires three features: I (^) Data abstraction with classes (encapsulation) I (^) Inheritance I (^) Dynamic method binding That last part, dynamic method binding, provides for subtype polymorphism, which we’ll learn today.
Let’s add SalariedEmployee to our class hierarchy. public final class SalariedEmployee3 extends Employee3 { private static final int MONTHS_PER_YEAR = 12; private final double annualSalary; public SalariedEmployee3(String aName, Date aHireDate, double anAnnualSalary) { super(aName, aHireDate); Disallowzeroesandnegatives(anAnnualSalary); annualSalary = anAnnualSalary; } public double getAnnualSalary() { return annualSalary; } public double monthlyPay() { return annualSalary / MONTHS_PER_YEAR; } // ... }
We now have all the classes in our hierarchy:
Employee
SalariedEmployee HourlyEmployee
But our classes aren’t well factored. I (^) SalariedEmployee3 and HourlyEmployee3 have duplicate copies of disallowZeroesAndNegatives I (^) SalariedEmployee3 and HourlyEmployee3 both have monthlyPay methods, but these methods are not polymorphic because they’re not defined in Employee Let’s refactor our Employee class hierarchy to give it a clean object-oriented design.
With our current class hierarchy, we need to maintain separate (partial) arrays of hourly and salaried employees. Because they’re partial arrays we also need to keep track of how many of each type of employee we have. public class Company { private HourlyEmployee[] hourlyEmployees; private int numHourlyEmployees = 10; private SalariedEmployee[] salariedEmployees; private int numSalariedEmployees = 10; public Company() { hourlyEmployees = new HourlyEmployee[numHourlyEmployees]; salariedEmployees = new SalariedEmployee[numSalariedEmployees]; } }
With our employee lists, calculating payroll is accomplished with two loops: public class Company { // hypothetical public double monthlyPayroll() { double payroll = 0.0; for (int i = 0; i < numHourlyEmployees; ++i) { payroll += hourlyEmployees[i].monthlyPay(); } for (int i = 0; i < numSalariedEmployees; ++i) { payroll += salariedEmployees[i].monthlyPay(); } return payroll; } // .. } Seems reasonable. But... I (^) What if we want to add a third type of employee?
The first step is to store one array of Employee s: public class Company4 { private Employee4[] employees; public Company4() { employees = ...; } public double monthlyPayroll() { double payroll = 0.0; for (int i = 0; i < employees.length; ++i) { payroll += employees[i].monthlyPay(); } return payroll; } } Much better. But it doesn’t compile. Why? $ javac Company.java Company.java:15: cannot find symbol symbol : method monthlyPay() location: class Employee payroll += employees[i].monthlyPay();
We need Employee to declare a monthlyPay method for subclasses to define. Since we don’t have a general definition for monthlyPay suitable for Employee, Employee will need to be abstract. public abstract class Employee4 { // ... public abstract double monthlyPay(); } An abstract class I (^) cannot be instantiated, I (^) may contain zero or more abstract methods, and I (^) subclasses must either provide an implementation for abstract methods, or be declared abstract themselves. This makes sense for our Employee4 class. We don’t ever want to instantiate Employee4 objects. Employee4 simply defines the common aspects of all employees, with subclasses filling in the details.
public class Company4 { private Employee4[] employees; public double monthlyPayroll() { double payroll = 0.0; for (Employee4 employee: employees) { payroll += employees.monthlyPay(); } return payroll; } } I (^) The static type of the elements of employees is Employee I (^) The dynamic type can be any subclass of Employee4, in this case they are all SalariedEmployee4 and HourlyEmployee I (^) When a method is invoked on an object, the method of the dynamic (run-time) type is used, no matter what the static (compile-time) type is. I (^) So though the static types of employees elements is Employee, the monthlyPay methods invoked on them are the ones defined in SalariedEmployee4 and HourlyEmployee4.
Recall the definition of disallowZeroesAndNegatives: private void disallowZeroesAndNegatives(double ... args) { boolean shouldThrowException = false; String nonPositives = ""; for (double arg: args) { if (arg <= 0.0) { shouldThrowException = true; nonPositives += arg + " "; } } if (shouldThrowException) { String msg = "Following arguments were <= 0: " + nonPositives; throw new IllegalArgumentException(msg); } } I (^) This method is duplicated in HourlyEmployee4 and SalariedEmployee I (^) Let’s move the definition of disallowZeroesAndNegatives into Employee5 so it will be shared (rather than duplicated) in SalariedEmployee5 and HourlyEmployee5.
Recall the disallowZeroesAndNegatives method that we refactored so that it’s in the Employee class and inherited by subclasses: public abstract class Employee6 { protected void disallowZeroesAndNegatives(double ... args) { // ... } } I (^) There’s nothing about this method that is specific to ~Employee~s I (^) disallowZeroesAndNegatives could be useful in other classes that are not part of the Employee class hierarchy. I (^) Since it’s protected, it can’t be used outside of the Employee class hierarchy or package. In software engineering terms, we say that the code in Employee lacks cohesion - it has parts that aren’t part of the Employee concept. Such a design hinders reuse.
If we move these protected methods into a separate class, like ../code/employee/ValidationUtils.java public class ValidationUtils { public static void disallowNullArguments(Object ... args) { ... } public static void disallowZeroesAndNegatives(double ... args) { ... } } we can use them anywhere, e.g., public Employee(String aName, Date aHireDate) { ValidationUtils.disallowNullArguments(aName, aHireDate); name = aName; hireDate = aHireDate; } With this refactoring, we have our final versions of Employee.java, HourlyEmployee.java, and SalariedEmployee.java
With encapsulation, inheritance, and polymorphism we have all the language features we need to employ three important object-oriented design principles: I (^) S ingle responsiblity principle: a module should only contain code related to the definition of the module I (^) Employee classes contain only employee-related code, validation code is in utility class I (^) O pen-closed principle: open for extension, closed for modification I (^) Can add new Employee subclasses without changing other classes in the Employee hierarchy or classes that use Employee~s, such as ~Company I (^) L liskov substitution principle: instances of subtypes should be substitutable wherever instances of supertypes are expected I (^) A square is not a rectangle in an OO sense, but both are 2-D shapes In CS 2340 you’ll learn several more OO design principles and several patterns that employ them.