Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

nheritance and Polymorphism A company pays its employees on a weekly basis. The

ID: 3685830 • Letter: N

Question

nheritance and Polymorphism A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay (1.5 * wage) for all hours worked in the excess of 40 hours, commission employees are paid a percentage of their sales and base-commission employees receive a base salary plus a commission based on their gross sales. The company wants to implement a java application that performs its payroll calculations polymorphically. (50 points) Employee hierarchy UML Class diagram 1. Write an Abstract Java class – Employee that encapsulates an employee’s first name, last name, SSN. Implement the appropriate get and set methods along with toString( ) method and equals( ) method. Note: An abstract class is a class that cannot be instantiated. The class is declared as follows: public abstract class Employee Also provide an abstract method called getEarnings( ) with return type of double type. The purpose of the getEarnings( ) method is to return the earnings that each type of employee makes. Note: an abstract method is a method with no body. Below is it’s declaration public abstract double getEarnings( ) ; 2. Create a Java class – SalariedEmployee which is a special type of Employee with the following additional attribute: weeklySalary. Provide appropriate get, set and equals( ), toString( ) methods. Implement a newer version of getEarnings( ) method that returns the earnings of SalariedEmployee: weeklySalary. 3. Create another Java class – HourlyEmployee which is another special type of Employee with the additional attributes: wage and hours. Provide appropriate set and get methods along with equals( ), toString method. Also implement a newer version of getEarnings( ) method that reflects earnings of HourlyEmployee. (Note: take into the account the rules for calculating the earnings for hourly employee as stated earlier in the problem description) 4. Create Java class – CommissionEmployee, another type of employee with attributes: grossSales and commissionRate. Provide set, get and equals( ), toString( ) methods. Provide a newer version of getEarnings( ) method that returns the earnings as (commissionRate * grossSales). 5. Implement a specialized type of CommissionEmployee called BasePlusCommissionEmployee class which has an additional attribute: base salary. Provide get, set and equals( ), toString( ) methods. Implement the getEarnings( ) method that returns the earnings as (commissionRate * grossSales) + baseSalary.

Explanation / Answer

import java.util.Random;

public class GenerateEmployees {
  
  
    //array of first names
    private final static String[] firstNames = { "George", "John", "Rutherford",
        "Franklin", "Ulysses", "Marsha", "Sue", "Charolett", "Brenda",
        "LaFonda" };
  
  
    //array of last names
    private final static String[] lastNames = { "Washington", "Adams", "Hayes",
        "Pierce", "Grant", "Billings", "Polk", "Kennedy", "Harrison", "Smith"};
    private static Employee[] generateEmployees(){
      
        //array that will hold random employee objects
        Employee[] employeeList = new Employee[10];
        Random rand = new Random();
      
        for(int i = 0; i < employeeList.length; i++){
            //chooses which type of employee and generates fields common to all
            int type = rand.nextInt(4);
            String firstName = firstNames[rand.nextInt(10)];
            String lastName = lastNames[rand.nextInt(10)];
            int SSN = (rand.nextInt(89999999) + 10000000);
          
            //creates objects of diferent classes depending on the randomly
            //generated number
            switch (type){
              
                //Salaried employee
                case 0:
                    double weeklySalary = rand.nextDouble() * 1500;

                    employeeList[i] = new SalariedEmployee
                            (firstName,
                            lastName,
                            SSN,
                            weeklySalary);
                  
                    break;
                
                  
                //Hourly employee
                case 1:
                    double wage = rand.nextDouble() * 40 + 7.25;
                    double hours = rand.nextDouble() * 80;
                  
                    employeeList[i] = new HourlyEmployee(
                            firstName,
                            lastName,
                            SSN,
                            wage,
                            hours);
                  
                    break;
                  
                //Commission Employee
                case 2:
                    double commissionRate = rand.nextDouble();
                    double grossSales = rand.nextDouble() * 5000;
                  
                    employeeList[i] = new CommissionEmployee(
                        firstName,
                        lastName,
                        SSN,
                        commissionRate,
                        grossSales);
                  
                    break;
                  
                  
                //Base Plus Commission Employee
                case 3:
                    double basePlusCommissionRate = rand.nextDouble();
                    double basePlusGrossSales = rand.nextDouble() * 5000;
                    double baseSalary = rand.nextDouble() * 500;
                  
                    employeeList[i] = new BasePlusCommissionEmployee(
                        firstName,
                        lastName,
                        SSN,
                        basePlusCommissionRate,
                        basePlusGrossSales,
                        baseSalary);
            }
        }
        return employeeList;
    }
  
    //Prints summary of each object in the array list
    public static void main(String[] args) {
        Employee[] employeeList = generateEmployees();
      
        for (Employee Obj : employeeList) {
            System.out.println(Obj.toString());
            System.out.println("");
        }
    }
}


Employee.java
import java.text.DecimalFormat;
import java.text.NumberFormat;

public abstract class Employee{

    //common fields
    private String firstName;
    private String lastName;
    private int SSN;

    //formats for toString output
    NumberFormat money = NumberFormat.getCurrencyInstance();
    DecimalFormat percent = new DecimalFormat("%0.##");
    public Employee(){
            this.firstName = "No Entry";
            this.lastName = "No Entry";
            this.setSSN(10000000);
    }
    public Employee(String xFirstName, String xLastName, int xSSN){
            this.firstName = xFirstName;
            this.lastName = xLastName;
            this.setSSN(xSSN);
    }
    public String getFirstName(){
            return this.firstName;
    }
    public String getLastName(){
            return this.lastName;
    }
    public int getSSN(){
            return this.SSN;
    }
    public void setFirstName(String xFirstName){
            this.firstName = xFirstName;
    }
    public void setLastName(String xLastName){
            this.lastName = xLastName;
    }

    /**
     * Sets the Social Security Number for the employee
     *
     * @param xSSN New Social Security Number for the employee
     */
    public final void setSSN(int xSSN){
        if(xSSN >= 10000000)
            this.SSN = xSSN;
        else
            throw new IllegalArgumentException("Must be an 8 digit number");
    }

/**************************************************************************/


    /**
     * Abstract method to return the earnings of the employee
     *
     * @return
    */
    public abstract double getEarnings();

    /**
     * Returns a printable version of the first/last name and SSN
     *
     * @return Printable version of the first/last name and SSN
     */
    @Override
    public String toString(){
        String output = "";
        output += "First name: " + this.firstName;
        output += " Last name: " + this.lastName;
        output += " Social Security Number: " + this.SSN;
        return output;
    }
  
  
  
    /**
     * Compares two Employee objects for equality by comparing all fields
     *
     * @param xObj Object to be compared
     * @return True if objects are equal, false if not
     */
    @Override
    public boolean equals(Object xObj){
        if (!(xObj instanceof Employee))
            return false;
        Employee Obj = (Employee)xObj;
        if (!(this.firstName.equals(Obj.getFirstName())))
            return false;
        if (!(this.lastName.equals(Obj.getLastName())))
            return false;
        return (this.SSN == Obj.getSSN());
    }
}

CommissionEmployee.java
public class CommissionEmployee extends Employee{


    //instance variables
    private double commissionRate;
    private double grossSales;
  
  

    /**
     * Default constructor
     * <p>
     * Initializes first/last name to "No Entry", SSN to 10000000, grossSales to
     * 0, and commissionRate to 0
     */
    public CommissionEmployee() {
        super();
        this.commissionRate = 0;
        this.grossSales = 0;
    }

  
  
    /**
     * Overloaded constructor
     * <p>
     * Initializes all fields with values from arguments
     *
     * @param xFirstName First name of the employee
     * @param xLastName Last name of the employee
     * @param xSSN Social security number of the employee
     * @param xCommissionRate Commission rate of the employee
     * @param xGrossSales Total sales for the week made by the employee
     */
    public CommissionEmployee(String xFirstName, String xLastName, int xSSN,
            double xCommissionRate, double xGrossSales) {
        super(xFirstName, xLastName, xSSN);
        this.setCommissionRate(xCommissionRate);
        this.setGrossSales(xGrossSales);
    }

  
  
    /**
     * Returns the commission rate of the employee
     *
     * @return Commission rate of the employee
     */
    public double getCommissionRate() {
        return commissionRate;
    }

  
  
    /**
     * Returns the gross sales of the employee
     *
     * @return Gross sales of the employee
     */
    public double getGrossSales() {
        return grossSales;
    }

  
  
    /**
     * Returns the earnings for the week of the employee
     *
     * @return Earnings for the week of the employee
     */
    @Override
    public double getEarnings() {
        return (commissionRate * grossSales);
    }

  
  
    /**
     * Sets the commission rate of the employee
     *
     * @param xCommissionRate New commission rate for the employee
     */
    public final void setCommissionRate(double xCommissionRate) {
        if (xCommissionRate < 0 || xCommissionRate > 1)
            throw new IllegalArgumentException("Rate must be a positive " +
                    "number");
        else
            commissionRate = xCommissionRate;
    }


  
     /**
     * Sets the gross sales of the employee
     *
     * @param xGrossSales New gross sales for the employee
     */
    public final void setGrossSales(double xGrossSales) {
        if (xGrossSales >= 0)
            grossSales = xGrossSales;
        else
            throw new IllegalArgumentException("Sales must be a positive " +
                    "number");
    }

    /**
     * Returns a printable version of the data contained in the object
     *
     * @return String containing printable version of the data in the object
     */
    @Override
    public String toString() {
        String output = "Type: Commission Employee";
        output += " " + super.toString();
        output += " Commission rate: " + percent.format(this.commissionRate);
        output += " Gross sales: " + money.format(this.grossSales);
        output += " Earnings: " + money.format(this.getEarnings());
        return output;
    }
  
  
  
    /**
     * Returns a printable version of the data contained in the class without
     * the type of the class
     * <p>
     * This is for use in the subclass. It allows the subclass to add its type
     * to the beginning of the string for its toString method.
     *
     * @return String containing all data in the class except for type of
     * employee
     */
    public String toStringNoType() {
        String output = super.toString();
        output += " Commission rate: " + percent.format(this.commissionRate);
        output += " Gross sales: " + money.format(this.grossSales);
        output += " Earnings: " + money.format(this.getEarnings());
        return output;
    }
  
  
  
    /**
     * Compares two CommissionEmployee objects for equality by comparing all
     * fields
     *
     * @param xObj Object to be compared
     * @return True if objects are equal, false if not
     */
    @Override
    public boolean equals(Object xObj){
        if (!(super.equals(xObj)))
            return false;
        if (!(xObj instanceof CommissionEmployee))
            return false;
        CommissionEmployee Obj = (CommissionEmployee) xObj;
      
        if (this.commissionRate != Obj.getCommissionRate())
            return false;
        return (this.grossSales == Obj.getGrossSales());
    }
}

BasePlusCommissionEmployee.java
public class BasePlusCommissionEmployee extends CommissionEmployee{
  
  
    //instance variable
    private double baseSalary;
  
  
  
    /**
     * Default constructor
     * <p>
     * Initializes first/last names to "No entry", SSN to 100000000, and
     * commissionRate, grossSales, and baseSalary to 0
     */
    public BasePlusCommissionEmployee(){
        super();
        this.baseSalary = 0;
    }
  
  
    /**
     * Overloaded constructor
     * <p>
     * Contains parameters for all fields
     *
     * @param xFirstName first name of the employee
     * @param xLastName last name of the employee
     * @param xSSN Social Security Number of the employee
     * @param xCommissionRate commission rate of the employee
     * @param xGrossSales gross sales of the employee
     * @param xBaseSalary base salary of the employee
     */
    public BasePlusCommissionEmployee(String xFirstName,
                                      String xLastName,
                                      int xSSN,
                                      double xCommissionRate,
                                      double xGrossSales,
                                      double xBaseSalary){
        super(xFirstName, xLastName, xSSN, xCommissionRate, xGrossSales);
        this.setBaseSalary(xBaseSalary);
    }
  
  
  
    /**
     * Returns the base salary of the employee
     *
     * @return Base salary of the employee
     */
    public double getBaseSalary(){
        return this.baseSalary;
    }
  
  
  
    /**
     * Returns the earnings for the week of the employee
     *
     * @return Earnings for the week for the employee
     */
    @Override
    public double getEarnings(){
        return (super.getEarnings() + baseSalary);
    }
  
  
  
    /**
     * Sets the base salary of the employee
     *
     * @param xBaseSalary new base salary of the employee
     */
    public final void setBaseSalary(double xBaseSalary){
        if(xBaseSalary >= 0)
            this.baseSalary = xBaseSalary;
        else
            throw new IllegalArgumentException("Base salary needs to be a " +
                    "positive number");
    }
  
  
  
    /**
     * Returns a printable version of the data contained in the object
     *
     * @return String containing printable version of data
     */
    @Override
    public String toString(){
        String output = "Type: Base Plus Commission Employee";
        output += " " + super.toStringNoType();
        output += " Base Salary: " + money.format(this.getBaseSalary());
        return output;
    }
  
  
  
    /**
     * Compares two BasePlusCommissionEmployee objects for equality by comparing
     * all fields
     *
     * @param xObj Object to be compared
     * @return True if objects are equal, false if not
     */
    @Override
    public boolean equals(Object xObj){
        if (!(super.equals(xObj)))
            return false;
        if (!(xObj instanceof BasePlusCommissionEmployee))
            return false;
        BasePlusCommissionEmployee Obj = (BasePlusCommissionEmployee) xObj;
        return (this.baseSalary == Obj.getBaseSalary());
    }
}                                                               

HourlyEmployee.java
import java.text.DecimalFormat;

public class HourlyEmployee extends Employee{


    //instance variables
    private double wage;
    private double hours;

    DecimalFormat decimal = new DecimalFormat("0.##");

    /**
     * Default constructor
     * <p>
     * Creates a new object with first/last name set to "No Entry",
     * SSN set to 100000000, and wage/hours to 0
     */
    public HourlyEmployee(){
            super();
            this.wage = 0;
            this.hours = 0;
    }

    /**
     * Overloaded constructor
     * <p>
     * Creates a new object with values for all fields
     *
     * @param xFirstName First name of the employee
     * @param xLastName Last name of the employee
     * @param xSSN Social Security Number of the employee
     * @param xWage Hourly wage of the employee
     * @param xHours Hours worked for the week by the employee
     */
    public HourlyEmployee(String xFirstName, String xLastName, int xSSN,
            double xWage, double xHours){
        super(xFirstName, xLastName, xSSN);
        setWage(xWage);
        setHours(xHours);
    }

    /**
     * Returns the hourly wage of the employee
     *
     * @return Hourly wage of the employee
     */
    public final double getWage(){
            return wage;
    }

    /**
     * Returns the number of hours worked by the employee
     *
     * @return Number of hours worked by the employee
     */
    public final double getHours(){
            return this.hours;
    }

    /**
     * Returns the total earnings of the employee for the week
     *
     * @return Earnings for the week of the employee
     */
    @Override
    public double getEarnings(){
        double pay = 0;

        //if employee has worked overtime
        if (this.hours > 40){
            this.hours -= 40;
            pay += 1.5 * hours * wage;
            pay += 40 * wage;
        }

        //if employee has not worked overtime
        else
            pay = this.hours * this.wage;

        return pay;
    }

    /**
     * Sets the number of hours the employee worked during the week
     *
     * @param xHours New number of hours worked for the week
     */
    public final void setHours(double xHours){
        if (xHours < 0)
            throw new IllegalArgumentException("Needs to be a positive number");
        if (xHours > 168)
            throw new IllegalArgumentException("There aren't that many hours "
                        + "in a week");
        this.hours = xHours;
    }

    /**
     * Sets the hourly wage earned by the employee
     *
     * @param xWage New hourly wage for the employee
     */
    public final void setWage(double xWage){
        if (xWage < 0)
            throw new IllegalArgumentException("Can't be paid a negative "
                    + "amount");
        if (xWage < 7.25)
            throw new IllegalArgumentException("That is below the federal " +
                    "minimum wage");
        wage = xWage;
    }

    /**
     * Returns a printable version of the data contained in the object
     *
     * @return String containing printable version of object data
     */
    @Override
    public String toString(){
        String output = "Type: Hourly Employee";
        output += " " + super.toString();
        output += " Hourly wage: " + money.format(this.wage);
        output += " Hours worked: " + decimal.format(this.hours);
        output += " Earnings: " + money.format(this.getEarnings());
        return output;
    }
    public boolean equals(Object xObj){
        if (!(super.equals(xObj)))
            return false;
        if (!(xObj instanceof HourlyEmployee))
            return false;
        HourlyEmployee Obj = (HourlyEmployee) xObj;
        if (this.hours != Obj.getHours())
            return false;
        return (this.wage == Obj.getWage());
    }
}

SalariedEmployee.java
public class SalariedEmployee extends Employee{


    //instance variable
    private double weeklySalary;
    public SalariedEmployee(){
        super();
        weeklySalary = 0.0;
    }
    public SalariedEmployee(String xFirstName, String xLastName, int xSSN,
                                double xWeeklySalary){
        super(xFirstName, xLastName, xSSN);
        this.setWeeklySalary(xWeeklySalary);
    }
    public double getEarnings(){
        return weeklySalary;
    }
    public final void setWeeklySalary(double xWeeklySalary){
        if(xWeeklySalary > 0)
            weeklySalary = xWeeklySalary;
        else
            throw new IllegalArgumentException("Needs to be a positive " +
                            "number");
    }
    @Override
    public String toString(){
        String output = "Type: Salaried Employee";
        output += " " + super.toString();
        output += " Earnings: " + money.format(this.getEarnings());
        return output;
    }
    @Override
    public boolean equals(Object xObj){
        if(!(super.equals(xObj)))
            return false;
        if(!(xObj instanceof SalariedEmployee))
                return false;
        SalariedEmployee Obj = (SalariedEmployee)xObj;
        return(this.weeklySalary == Obj.getEarnings());
    }
}


sample output

Type: Salaried Employee                                                                                                                                     
First name: Charolett                                                                                                                                       
Last name: Polk                                                                                                                                             
Social Security Number: 48756816                                                                                                                            
Earnings: $1,298.86                                                                                                                                         
                                                                                                                                                            
Type: Salaried Employee                                                                                                                                     
First name: George                                                                                                                                          
Last name: Polk                                                                                                                                             
Social Security Number: 55580561                                                                                                                            
Earnings: $246.49                                                                                                                                           
Type: Base Plus Commission Employee                                                                                                                         
First name: Brenda                                                                                                                                          
Last name: Grant                                                                                                                                            
Social Security Number: 14605203                                                                                                                            
Commission rate: %30.98                                                                                                                                     
Gross sales: $116.83                                                                                                                                        
Earnings: $150.73                                                                                                                                           
Base Salary: $114.53