Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: My polymorphism code won't work

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default My polymorphism code won't work

    Doing some work on polymorphism. I want to set a birthdate, hiredate and assign a bonus based on the month of year we're in. The problem I am coming across is the hireDate is showing up as null for some reason. Everything else is working fine, though. They made us write a custom date application and they want us to use that for this example, but I would like to know how to incorporate the built in Date class in Java. How can I do this with this code.

    Output currently:

    Employees processed individually:
     
    salaried employee: Bill Williams
     Social Security Number: 123-45-6789
     Birth Date: 12/7/1975
     Hire Date: null
    weekly salary: $10,800.00
    birth date: 12/7/1975
    earned: $10,800.00
     
    hourly employee: Karen Johnson
     Social Security Number: 987-65-4321
     Birth Date: 12/31/1980
     Hire Date: null
    hourly wage: $16.75; hours worked: 40.00
    earned: $670.00
     
    hourly employee: Wilma Flintstone
     Social Security Number: 387-63-4331
     Birth Date: 1/30/1987
     Hire Date: null
    hourly wage: $16.75; hours worked: 60.00
    earned: $1,172.50
     
    commission employee: Betty Rubble
     Social Security Number: 234-56-7890
     Birth Date: 8/9/1980
     Hire Date: null
    gross sales: $10,000.00; commission rate: 0.60
    earned: $6,000.00
     
    base-salaried commission employee: George Jetson
     Social Security Number: 345-67-8901
     Birth Date: 2/29/1981
     Hire Date: null
    gross sales: $6,000.00; commission rate: 0.50; base salary: $500.00
    earned: $3,500.00
     
    Employees processed polymorphically: 
     
    salaried employee: Bill Williams
     Social Security Number: 123-45-6789
     Birth Date: 12/7/1975
     Hire Date: null
    weekly salary: $10,800.00
    birth date: 12/7/1975
    earned $10800.00,
     
    hourly employee: Karen Johnson
     Social Security Number: 987-65-4321
     Birth Date: 12/31/1980
     Hire Date: null
    hourly wage: $16.75; hours worked: 40.00
    earned $670.00,
     
    hourly employee: Wilma Flintstone
     Social Security Number: 387-63-4331
     Birth Date: 1/30/1987
     Hire Date: null
    hourly wage: $16.75; hours worked: 60.00
    earned $1172.50,
     
    commission employee: Betty Rubble
     Social Security Number: 234-56-7890
     Birth Date: 8/9/1980
     Hire Date: null
    gross sales: $10,000.00; commission rate: 0.60
    earned $6000.00,
     
    base-salaried commission employee: George Jetson
     Social Security Number: 345-67-8901
     Birth Date: 2/29/1981
     Hire Date: null
    gross sales: $6,000.00; commission rate: 0.50; base salary: $500.00
    new base salary with 10% increase is: $550.00
    earned $3550.00,
     
    Employee 0 is a SalariedEmployee
    Employee 1 is a HourlyEmployee
    Employee 2 is a HourlyEmployee
    Employee 3 is a CommissionEmployee2
    Employee 4 is a BasePlusCommissionEmployee2

    public class BasePlusCommissionEmployee2 extends CommissionEmployee2 
    {
    	private double baseSalary; //base salary per week
     
    	//six argument constructor
        public BasePlusCommissionEmployee2( String first, String last,
                String ssn, double sales, double rate, double salary, String birth, String hire, int month) 
        {
            super( first, last, ssn, sales, rate, birth, hire, month);
            setBaseSalary( salary );
        }//end six-argument constructor
     
    	//set baseSalary
    	public void setBaseSalary(double salary)
    	{
    		if(salary >= 0.0)
    			baseSalary = salary;
    		else
    			throw new IllegalArgumentException("Base Salary must be more than 0.0");
    	}//end method setBaseSalary
     
    	//return base salary
    	public double getBaseSalary()
    	{
    		return baseSalary;
    	}//end method getBaseSalary
     
    	//calculate earning; override method earnings in CommissionEmployee
    	@Override
    	public double earnings()
    	{
    		return getBaseSalary() + super.earnings();
    	}//end method earnings
     
    	//return String representation of BasePlusCommissionEmployee object 
    	public String toString()
    	{
    		return String.format( "%s %s; %s: $%,.2f",
    				"base-salaried", super.toString(),
    				"base salary", getBaseSalary() );
    	} // end method toString
    }//end class CommissionEmployee2

    public class CommissionEmployee2 extends EmployeeAbstract
    {
    	private double grossSales; //gross sales 
    	private double commissionRate; //commission rate percentage
     
    	//five-argument constructor
        public CommissionEmployee2( String first, String last, String ssn,
                double sales, double rate, String birth, String hire, int month ) {
            super( first, last, ssn, birth, hire, month);
            setGrossSales( sales );
            setCommissionRate( rate );
        }
     
    	//set CommissionRate
    	public void setCommissionRate(double rate)
    	{
    		if(rate > 0.0 && rate < 1.0)
    			commissionRate = rate;
    		else
    			throw new IllegalArgumentException("Commission rate must be between 0.0 and 1.0");
    	}//end method setCommissionRate
     
    	//return commissionRate for our use
    	public double getCommissionRate()
    	{
    		return commissionRate;
    	}//end method getCommissionRate
     
    	//set GrossSales
    	public void setGrossSales(double sales)
    	{
    		if(sales >= 0.0)
    			grossSales = sales;
    		else
    			throw new IllegalArgumentException("Gross sales must be more than 0.0");
    	}//end method setGrossSales
     
    	//return GrossSales for our use
    	public double getGrossSales()
    	{
    		return grossSales;
    	}//end method getGrossSales
     
    	//calculate earnings; override abstract method earnings in Employee
    	@Override
    	public double earnings()
    	{
    		return getCommissionRate() * getGrossSales();
    	}//end method earnings
     
    	//return String representation of CommissionEmployee object
    	@Override
    	public String toString()
    	{
    		return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",
    				"commission employee", super.toString(),
    				"gross sales", getGrossSales(),
    				"commission rate", getCommissionRate() );
    	} // end method toString
     
    }//end class CommissionEmployee2

    //Date class declaration
    public class Date
    {
    	private int month; //1 -12
    	private int day; //1-31 based on month
    	private int year; // any year
     
    	private static final int[] daysPerMonth =//days in each month
    	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
     
    	//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;//to validate year
    		day = checkDay(theDay); //validate day
     
    		System.out.printf("Date object constructor for date %s\n", this);
    	}//end constructor Date
     
    	//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
    			throw new IllegalArgumentException("month must be 1-12");
    	}//end method checkMonth
     
    	//utility method to confirm proper day value based on month and year
    	private int checkDay(int testDay)
    	{
    		//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;
     
    		throw new IllegalArgumentException("day out-of-range for the specified month and year");
    	}//ebd method checkDay
     
    	public int getMonth()
    	{
    		return month;
    	}//end method getMonth
     
    	public int getDay()
    	{
    		return day;
    	}//end method getDay
     
    	public int getYear()
    	{
    		return year;
    	}//end method getMonth
     
    	//return a String of the form month/day/year
    	public String toString()
    	{
    		return String.format("%d/%d/%d", month, day, year);
    	}//method toString
    }//end class Date

    public abstract class EmployeeAbstract
    {
    	private String firstName;
    	private String lastName;
    	private String socialSecurityNumber;
    	private String birthDate;
    	private String hireDate;
    	private int birthMonth;
     
     
    	//three-argument constructor
    	public EmployeeAbstract(String first, String last, String ssn, String birth, String hire, int Month)
    	{
    		firstName = first;
    		lastName = last;
    		socialSecurityNumber = ssn;
    		birthDate = birth;
    		birthMonth = Month;
     
    	}//end three-argument constructor
     
    	//get and set method for first name
    	public void setFirstName(String first)
    	{
    		firstName = first;
    	}//end method setfirstName
     
    	public String getFirstName()
    	{
    		return firstName;
    	}//end method getFirstName
     
    	//get and set method for last name
    	public void setLastName(String last)
    	{
    		lastName = last;
    	}//end method setLastName
     
    	public String getLastName()
    	{
    		return lastName;
    	}//end method getLastName
     
    	//get and set method for social security number
    	public void setSocialSecurityNumber(String ssn)
    	{
    		socialSecurityNumber = ssn;
    	}//end method setSocialSecurityNumber
     
    	public String getSocialSecurityNumber()
    	{
    		return socialSecurityNumber;
    	}//end method getSocialSecurityNumber
     
     
    	public String getBirthDate()
    	{
    		return birthDate;
    	}
     
    	public String getHireDate()
    	{
    		return hireDate;
    	}
     
    	public int getbirthMonth()
    	{
    		return birthMonth;
    	}
    	//return String representation of Employee object
    	@Override
    	public String toString()
    	{
    		return String.format("%s %s\n Social Security Number: %s\n Birth Date: %s\n Hire Date: %s", getFirstName(), getLastName(), getSocialSecurityNumber(), getBirthDate(), getHireDate() );
    	}//end method toString
     
    	//abstract method overridden by concrete subclasses
    	public abstract double earnings();//no implimentation here
    }//end class EmployeeAbstract

    //Employee Hierarchy test
     
     
    public class PayRollTest 
    {
    	public static void main(String[] args)
    	{
    		//create subclass object
    		SalariedEmployee salariedEmployee = new SalariedEmployee("Bill", "Williams", "123-45-6789", 10800.00, "12/7/1975", "12/31/2003", 12);
    		HourlyEmployee hourlyEmployee = new HourlyEmployee("Karen", "Johnson", "987-65-4321", 16.75, 40, "12/31/1980", "3/4/2003", 12);
    		HourlyEmployee overTimeEmployee = new HourlyEmployee("Wilma", "Flintstone", "387-63-4331", 16.75, 60, "1/30/1987", "5/4/2007", 1);
    		CommissionEmployee2 commissionEmployee = new CommissionEmployee2("Betty", "Rubble", "234-56-7890", 10000, 0.6, "8/9/1980","9/10/2005", 8);
    		BasePlusCommissionEmployee2 BPCE2 = new BasePlusCommissionEmployee2("George", "Jetson", "345-67-8901", 6000, 0.5, 500, "2/29/1981", "6/6/2008", 2);
     
    		System.out.println("Employees processed individually:\n");
     
    		System.out.printf("%s\n%s: $%,.2f\n\n", salariedEmployee, "earned", salariedEmployee.earnings());
    		System.out.printf("%s\n%s: $%,.2f\n\n", hourlyEmployee, "earned", hourlyEmployee.earnings());
    		System.out.printf("%s\n%s: $%,.2f\n\n", overTimeEmployee, "earned", overTimeEmployee.earnings());
    		System.out.printf("%s\n%s: $%,.2f\n\n", commissionEmployee, "earned", commissionEmployee.earnings());
    		System.out.printf("%s\n%s: $%,.2f\n\n", BPCE2, "earned", BPCE2.earnings());
     
    		//create an array for our employees
    		EmployeeAbstract[] employees = new EmployeeAbstract[5];
     
    		//initialize array with Employee
    		employees[0] = salariedEmployee;
    		employees[1] = hourlyEmployee;
    		employees[2] = overTimeEmployee;
    		employees[3] = commissionEmployee;
    		employees[4] = BPCE2;
     
    		System.out.println("Employees processed polymorphically: \n");
     
    		//generally process each element in array employees
    		for(EmployeeAbstract currentEmployee : employees)
    		{
    			System.out.println(currentEmployee); //invokes toString
     
    			//determine if element is a BasePlusCommissionEmployee
    			if(currentEmployee instanceof BasePlusCommissionEmployee2)
    			{
    				//downcast Employee reference to
    				//BasePlusCommissionEmployee reference
    				BasePlusCommissionEmployee2 employee = (BasePlusCommissionEmployee2) currentEmployee;
     
    				employee.setBaseSalary(1.10 * employee.getBaseSalary());
     
    				System.out.printf("new base salary with 10%% increase is: $%,.2f\n", employee.getBaseSalary());
    			}//end if
    			System.out.printf("earned $%.2f,\n\n", currentEmployee.earnings());
    		}//end for
     
    		//get type name of each  object in employees array
    		for(int j = 0; j < employees.length; j++ )
    			System.out.printf("Employee %d is a %s\n", j, employees[j].getClass().getName());
    	}//end main
    }//end PayRollTest


  2. #2
    Member
    Join Date
    Jan 2012
    Location
    Hellas
    Posts
    284
    Thanks
    11
    Thanked 59 Times in 57 Posts

    Default Re: My polymorphism code won't work

    Hello Floomer99!
    Quote Originally Posted by Floomer99 View Post
    The problem I am coming across is the hireDate is showing up as null for some reason.
    Look at your EmployeeAbstract class's constructor:
    public EmployeeAbstract(String first, String last, String ssn, String birth, String hire, int Month)
    	{
    		firstName = first;
    		lastName = last;
    		socialSecurityNumber = ssn;
    		birthDate = birth;
    		birthMonth = Month;
     
    	}
    You pass to the constructor a String hire, but you don't assign it to hireDate.

Similar Threads

  1. HI, could someone please tell me why my code doesnt work?
    By joelmeler in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 3rd, 2011, 02:37 AM
  2. Scanner code won't work
    By r19ecua in forum What's Wrong With My Code?
    Replies: 6
    Last Post: April 21st, 2011, 05:49 PM
  3. Timer code does not work!
    By mariapatrawala in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 10th, 2010, 10:03 AM
  4. WHY this code dont work?
    By sibbe in forum Java Theory & Questions
    Replies: 7
    Last Post: December 9th, 2010, 10:47 AM
  5. please tell me why this code does not work
    By amr in forum Java Theory & Questions
    Replies: 9
    Last Post: December 6th, 2010, 06:46 PM