Inheritance and Polymorphism
publicclass Employee {
private String name;
private String department;
privatedoublehourlyRate;
public Employee(String p_name,Stringp_dept, doublep_hourlyRate)
{
name = p_name;
department = p_dept;
hourlyRate= p_hourlyRate;
}
publicvoidsetDepartment(String p_dept)
{
department = p_dept;
}
publicvoidsetHourlyRate(doublep_rate)
{
hourlyRate = p_rate;
}
public String getNameAndDepartment()
{
return "Name:" + name + "\nDepartment:" + department;
}
publicdoubleWeeklyPay(intp_numberOfHoursWorked)
{
if(p_numberOfHoursWorked< 40)
returnp_numberOfHoursWorked * hourlyRate;
else
return 40 * hourlyRate;
}
}
publicclassUnionEmployee
extends Employee
{
privatedouble dues;
publicUnionEmployee(String p_name,Stringp_dept, doublep_hourlyRate,doublep_dues)
{
super(p_name,p_dept,p_hourlyRate);
dues = p_dues;
}
publicvoidsetDues(doublep_dues)
{
dues = p_dues;
}
publicdoubleWeeklyPay(intp_hoursWorked)
{
doubleweeklyPay = 0;
if(p_hoursWorked> 40)
{
weeklyPay = super.WeeklyPay(40);
weeklyPay = weeklyPay + (1.5 * (p_hoursWorked - 40)) - dues;
}
else
weeklyPay = super.WeeklyPay(p_hoursWorked);
returnweeklyPay;
}
}
publicclassCommissionedEmployee
extends Employee
{
privatedoublecommissionRate;
privatedoublesalesAmount;
publicCommissionedEmployee(String p_name,Stringp_dept, doublep_hourlyRate,doublep_commissionRate)
{
super(p_name,p_dept,p_hourlyRate);
commissionRate = p_commissionRate;
salesAmount = 0;
}
publicvoidsetCommissionRate(doublep_commissionRate)
{
commissionRate = p_commissionRate;
}
publicvoidsetSalesAmount(doublep_salesAmount)
{
salesAmount = p_salesAmount;
}
publicdoubleWeeklyPay(intp_numberOfHoursWorked)
{
doubleweeklyPay = super.WeeklyPay(p_numberOfHoursWorked);
weeklyPay = weeklyPay + (commissionRate * salesAmount);
returnweeklyPay;
}
}
publicclassTestClass {
/**
* @paramargs
*/
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
UnionEmployeeu_Emp = newUnionEmployee("UnionEmp1", "UnionDept1", 100, 50);
CommissionedEmployeec_Emp = newCommissionedEmployee("CommissionEmp2", "Commission Dept2", 100, 50.4);
c_Emp.setSalesAmount(2000);
System.out.println("Displaying Union Employee");
display(u_Emp,20);
display(u_Emp,40);
display(u_Emp,60);
System.out.println("Displaying Commissioned Employee");
display(c_Emp,20);
display(c_Emp,40);
display(c_Emp,60);
}
publicstaticvoid display(Employee p_emp, intp_numberOfHours)
{
System.out.println("Number of Hours:" + p_numberOfHours);
System.out.println(p_emp.getNameAndDepartment());
System.out.println("Weekly Pay:" +p_emp.WeeklyPay(p_numberOfHours));
System.out.println();
}
}