Solved

Add birthDate using polymorphism

Posted on 2003-11-05
6
920 Views
Last Modified: 2012-06-27
I am pretty new to java and am stumped on this problem in the book I am using.  I can not find an example of the solution anywhere so I have come here.  I will post my code, here is the problem:

Include a private instance variable birthDate in class Employee.  Assume that payroll is processed once per month.  Create an array of Employee variables to store references to the various employee objects.  In a loop, calculate the payroll for each Employee (polymorphically), and add a $100.00 bonus to the person's payroll amount if the current month is the month in which the Employee's birthday occurs.

Code:

// Date class declaration.

public class Date {
   private int month;  // 1-12
   private int day;    // 1-31 based on month
   private int year;   // any year

   // constructor: call checkMonth to confirm proper value for month;
   // call checkDay to confirm proper value for day
   public Date( int theMonth, int theDay, int theYear )
   {
      month = checkMonth( theMonth ); // validate month
      year = theYear;                 // could validate year
      day = checkDay( theDay );       // validate day

      System.out.println( "Date object constructor for date " +
         toDateString() );

   } // end Date constructor

   // utility method to confirm proper month value
   private int checkMonth( int testMonth )
   {
      if ( testMonth > 0 && testMonth <= 12 )  // validate month
         return testMonth;

      else { // month is invalid
         System.out.println( "Invalid month (" + testMonth +
            ") set to 1." );
         return 1;  // maintain object in consistent state
      }

   } // end method checkMonth

   // utility method to confirm proper day value based on month and year
   private int checkDay( int testDay )
   {
      int daysPerMonth[] =
         { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

      // check if day in range for month
      if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
         return testDay;

      // check for leap year
      if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
           ( year % 4 == 0 && year % 100 != 0 ) ) )
         return testDay;

      System.out.println( "Invalid day (" + testDay + ") set to 1." );

      return 1;  // maintain object in consistent state

   } // end method checkDay

   // return a String of the form month/day/year
   public String toDateString()
   {
      return month + "/" + day + "/" + year;
   }

} // end class Date

****************************************************************

// Employee abstract superclass.

public abstract class Employee {
   private String firstName;
   private String lastName;
   private String socialSecurityNumber;
   private Date birthDate;


   // constructor
   public Employee( String first, String last, String ssn, Date dateOfBirth )
   {
      firstName = first;
      lastName = last;
      socialSecurityNumber = ssn;
      birthDate = dateOfBirth;
   }

   // set first name
   public void setFirstName( String first )
   {
      firstName = first;
   }

   // return first name
   public String getFirstName()
   {
      return firstName;
   }

   // set last name
   public void setLastName( String last )
   {
      lastName = last;
   }

   // return last name
   public String getLastName()
   {
      return lastName;
   }

   // set social security number
   public void setSocialSecurityNumber( String number )
   {
      socialSecurityNumber = number;  // should validate
   }

   // return social security number
   public String getSocialSecurityNumber()
   {
      return socialSecurityNumber;
   }

   public Date setDateOfBirth( Date dateOfBirth )
   {
               birthDate = dateOfBirth;
   }

   public Date getDateOfBirth()
   {
                  return birthDate;
   }

   // return String representation of Employee object
   public String toString()
   {
      return getFirstName() + " " + getLastName() +
         "\nsocial security number: " + getSocialSecurityNumber() + " Birthday: " + birthDate.toDateString();
   }



   // abstract method overridden by subclasses
   public abstract double earnings();

} // end abstract class Employee

*************************************************************

// BasePlusCommissionEmployee class extends CommissionEmployee.

public class BasePlusCommissionEmployee extends CommissionEmployee {
   private double baseSalary;  // base salary per week

   // constructor
   public BasePlusCommissionEmployee( String first, String last,
      String socialSecurityNumber, double grossSalesAmount,
      double rate, double baseSalaryAmount )
   {
      super( first, last, socialSecurityNumber, grossSalesAmount, rate );
      setBaseSalary( baseSalaryAmount );
   }

   // set base-salaried commission employee's base salary
   public void setBaseSalary( double salary )
   {
      baseSalary = salary < 0.0 ? 0.0 : salary;
   }

   // return base-salaried commission employee's base salary
   public double getBaseSalary()
   {
      return baseSalary;
   }

   // calculate base-salaried commission employee's earnings;
   // override method earnings in CommissionEmployee
   public double earnings()
   {
      return getBaseSalary() + super.earnings();
   }

   // return String representation of BasePlusCommissionEmployee
   public String toString()
   {
      return "\nbase-salaried commission employee: " +
         super.getFirstName() + " " + super.getLastName() +
         "\nsocial security number: " + super.getSocialSecurityNumber();
   }

} // end class BasePlusCommissionEmployee

**************************************************************

// CommissionEmployee class extends Employee.

public class CommissionEmployee extends Employee {
   private double grossSales;      // gross weekly sales
   private double commissionRate;  // commission percentage

   // constructor
   public CommissionEmployee( String first, String last,
      String socialSecurityNumber,
      double grossWeeklySales, double percent )
   {
      super( first, last, socialSecurityNumber );
      setGrossSales( grossWeeklySales );
      setCommissionRate( percent );
   }

   // set commission employee's rate
   public void setCommissionRate( double rate )
   {
      commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
   }

   // return commission employee's rate
   public double getCommissionRate()
   {
      return commissionRate;
   }

   // set commission employee's weekly base salary
   public void setGrossSales( double sales )
   {
      grossSales = sales < 0.0 ? 0.0 : sales;
   }

   // return commission employee's gross sales amount
   public double getGrossSales()
   {
      return grossSales;
   }

   // calculate commission employee's pay;
   // override abstract method earnings in Employee
   public double earnings()
   {
      return getCommissionRate() * getGrossSales();
   }

   // return String representation of CommissionEmployee object
   public String toString()
   {
      return "\ncommission employee: " + super.toString();
   }

} // end class CommissionEmployee

**************************************************************

public class HourlyEmployee extends Employee {
   private double wage;   // wage per hour
   private double hours;  // hours worked for week

   // constructor
   public HourlyEmployee( String first, String last,
      String socialSecurityNumber, double hourlyWage, double hoursWorked )
   {
      super( first, last, socialSecurityNumber );
      setWage( hourlyWage );
      setHours( hoursWorked );
   }

   // set hourly employee's wage
   public void setWage( double wageAmount )
   {
      wage = wageAmount < 0.0 ? 0.0 : wageAmount;
   }

   // return wage
   public double getWage()
   {
      return wage;
   }

   // set hourly employee's hours worked
   public void setHours( double hoursWorked )
   {
      hours = ( hoursWorked >= 0.0 && hoursWorked <= 168.0 ) ?
         hoursWorked : 0.0;
   }

   // return hours worked
   public double getHours()
   {
      return hours;
   }

   // calculate hourly employee's pay;
   // override abstract method earnings in Employee
   public double earnings()
   {
      if ( hours <= 40 )  // no overtime
         return wage * hours;
      else
         return 40 * wage + ( hours - 40 ) * wage * 1.5;
   }

   // return String representation of HourlyEmployee object
   public String toString()
   {
      return "\nhourly employee: " + super.toString();
   }

} // end class HourlyEmployee

**************************************************************

// SalariedEmployee class extends Employee.

public class SalariedEmployee extends Employee {
   private double weeklySalary;

   // constructor
   public SalariedEmployee( String first, String last,
      String socialSecurityNumber, double salary )
   {
      super( first, last, socialSecurityNumber );
      setWeeklySalary( salary );
   }

   // set salaried employee's salary
   public void setWeeklySalary( double salary )
   {
      weeklySalary = salary < 0.0 ? 0.0 : salary;
   }

   // return salaried employee's salary
   public double getWeeklySalary()
   {
      return weeklySalary;
   }

   // calculate salaried employee's pay;
   // override abstract method earnings in Employee
   public double earnings()
   {
      return getWeeklySalary();
   }

   // return String representation of SalariedEmployee object
   public String toString()
   {
      return "\nsalaried employee: " + super.toString();
   }

} // end class SalariedEmployee

************************************************************

// Employee hierarchy test program.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class PayrollSystemTest {

   public static void main( String[] args )
   {
      DecimalFormat twoDigits = new DecimalFormat( "0.00" );

      // create Employee array
      Employee employees[] = new Employee[ 4 ];

      // initialize array with Employees
      employees[ 0 ] = new SalariedEmployee( "John", "Smith",
         "111-11-1111", 800.00, 2, 18, 1949 );
      employees[ 1 ] = new CommissionEmployee( "Sue", "Jones",
         "222-22-2222", 10000, .06, 10, 2, 1959 );
      employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis",
         "333-33-3333", 5000, .04, 300, 9, 15, 1964 );
      employees[ 3 ] = new HourlyEmployee( "Karen", "Price",
         "444-44-4444", 16.75, 40, 8, 15, 1962 );

      String output = "";

      // generically process each element in array employees
      for ( int i = 0; i < employees.length; i++ ) {
         output += employees[ i ].toString();

         // determine whether element is a BasePlusCommissionEmployee
         if ( employees[ i ] instanceof BasePlusCommissionEmployee ) {

            // downcast Employee reference to
            // BasePlusCommissionEmployee reference
            BasePlusCommissionEmployee currentEmployee =
               ( BasePlusCommissionEmployee ) employees[ i ];

            double oldBaseSalary = currentEmployee.getBaseSalary();
            output += "\nold base salary: $" + oldBaseSalary;

            currentEmployee.setBaseSalary( 1.10 * oldBaseSalary );
            output += "\nnew base salary with 10% increase is: $" +
               currentEmployee.getBaseSalary();

         } // end if

         output += "\nearned $" + employees[ i ].earnings() + "\n";

      } // end for

      // get type name of each object in employees array
      for ( int j = 0; j < employees.length; j++ )
         output += "\nEmployee " + j + " is a " +
            employees[ j ].getClass().getName();

      JOptionPane.showMessageDialog( null, output );  // display output
      System.exit( 0 );

   } // end main

} // end class PayrollSystemTest

0
Comment
Question by:brassmon
6 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9690458
so what exactly is your problem?
0
 
LVL 16

Assisted Solution

by:imladris
imladris earned 250 total points
ID: 9690468
This doesn't look like it compiles. For instance, the constructor for Employee is:

public Employee( String first, String last, String ssn, Date dateOfBirth )

But when the CommissionEmployee is constructed, its call to super (which is to the Employee constructor) doesn't have the same arguments!

public CommissionEmployee( String first, String last,
      String socialSecurityNumber,
      double grossWeeklySales, double percent )
   {
      super( first, last, socialSecurityNumber );
      setGrossSales( grossWeeklySales );
      setCommissionRate( percent );
   }

The super call in the CommissionEmployee will have to supply a birthdate to the Employee constructor. And that's reasonable, given the definitions. Since birthdate is part of the definition of the Employee class, and is part of the Employee constructor it is a data item that *every* Employee and *every* class derived from Employee has to provide. It's part of the "basic" definition of an employee.

Given that, you can, for any employee, call the getDateOfBirth method to determine if this month is the employees "birthmonth" and, if it is, add $100 to his salary.

None of the derived classes can access the private birthDate instance variable. They can, of course, access the public getDateOfBirth accessor method.
0
 

Accepted Solution

by:
saygin earned 250 total points
ID: 9692392
I think it probably won't compile. There are several problems

1] You probably need to have the following constructor in employee.java

   // constructor
   public Employee( String first, String last, String ssn) {

  }

Example

   // constructor
   public Employee( String first, String last, String ssn)
   {
      firstName = first;
      lastName = last;
      socialSecurityNumber = ssn;
      birthDate = new Date(1,1,2003); // set a default - change this if required
   }  

because the subclass of employee have calls

   super( first, last, socialSecurityNumber );
in its constructor

2]
   public Date setDateOfBirth( Date dateOfBirth )
   {
             birthDate = dateOfBirth;
   }

Should be

   public void setDateOfBirth( Date dateOfBirth )
   {
             birthDate = dateOfBirth;
   }

3] Try changing in PayrollSystemTest.java

      // initialize array with Employees
      //employees[ 0 ] = new SalariedEmployee( "John", "Smith","111-11-1111", 800.00, 2, 18, 1949 );
      //employees[ 1 ] = new CommissionEmployee( "Sue", "Jones","222-22-2222", 10000, .06, 10, 2, 1959 );
      //employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis","333-33-3333", 5000, .04, 300, 9, 15, 1964 );
      //employees[ 3 ] = new HourlyEmployee( "Karen", "Price","444-44-4444", 16.75, 40, 8, 15, 1962 );

To (because the constructor of each class excepts only the following arguments ... however, you can create the constructor in the classes that also takes in the day, month and year ... if you like) :

      employees[ 0 ] = new SalariedEmployee( "John", "Smith","111-11-1111", 800.00);
      employees[ 1 ] = new CommissionEmployee( "Sue", "Jones","222-22-2222", 10000, .06);
      employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis","333-33-3333", 5000, .04, 300 );
      employees[ 3 ] = new HourlyEmployee( "Karen", "Price","444-44-4444", 16.75, 40 );



0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 2

Expert Comment

by:override_y2k
ID: 9694575
Hmm this ,looks suspiciously like more homework.Thats the 3rd post ive seen looking for a similar solution to the good old employee example using polymorphism.

1st off do you know what polymorphism is?
0
 
LVL 16

Expert Comment

by:imladris
ID: 9702226
Did any of those answers help?

If so, it is now time to choose one and grade it.

If not, perhaps a clarifying question would help.
0
 
LVL 2

Expert Comment

by:override_y2k
ID: 9717415
I think the fct that it was awrded 500 points is further evidence of this!
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now