Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Add birthDate using polymorphism

Posted on 2003-11-05
6
Medium Priority
?
990 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 1000 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 1000 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses

824 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