问题描述:
某公司的雇员分为以下若干类:
1、Employee:这是所有员工总的父类,属性:员工的姓名,员工的生日月份。方法:getSalary(intmonth) 根据参数月份来确定工资,如果该月员工过生日,则公司会额外奖励100元。
2 SalariedEmployee:Employee的子类,拿固定工资的员工。属性:月薪
3HourlyEmployee:Employee的子类,按小时拿工资的员工,每月工作超出160小时的部分按照1.5倍工资发放。属性:每小时的工资、每月工作的小时数
4SalesEmployee:Employee的子类,销售人员,工资由月销售额和提成率决定。属性:月销售额、提成率
5BasePlusSalesEmployee : SalesEmployee 的子类,有固定底薪的销售人员,工资由底薪加上销售提成部分。属性:底薪。
可编写程序代码如下实现题目要求功能:
首先是Employee父类
public class Employee {
String name;
int month;
public double getSalary(double salary,int month){
if(this.month==month){//this关键字调用被隐藏的属性
return salary+100;
}else{
return salary;
}
}
}
下面是继承Employee父类的SalariedEmployee子类
public class SalariedEmployee extends Employee {//extends表示继承
double salary;//定义成员变量,该子类没有写成员方法,可以通过继承父类方法实现计算工资功能
}
下面是继承Employee父类的HourlyEmployee子类
public class HourlyEmployee extends Employee {
double time;
double timesalary;
public double getSalary(int month){//此处是对父类成员方法的重写
if(time>160){
return super.getSalary(160*timesalary+timesalary*1.5*(timesalary-160), month);//super关键字调用被隐藏的父类该成员方法
}else{
return super.getSalary(time*timesalary, month);
}
}
}
下面是继承Employee父类的SalesEmployee子类
public class SalesEmployee extends Employee {
private double monthlysales;//private实现对成员变量的封装,其他类中不可以直接访问该变量
private double rate;
public double getMonthlysales() {//该方法可以让外界获取私有变量的值
return monthlysales;
}
public void setMonthlysales(double monthlysales) {//该方法可以让外界给私有变量赋值
this.monthlysales = monthlysales;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getSalary(int month){//父类方法的重写
return super.getSalary(monthlysales*rate,month);
}
}
下面是继承SalesEmployee父类的BasePlusSalesEmployee子类
public class BasePlusSalesEmployee extends SalesEmployee {//该子类继承了父类SalesEmployee的所有非私有成员变量和成员方法,也继承了Employee类的所有非私有成员变量和成员方法
double salary;
public double getSalary(int month){//对父类SalesEmployee成员方法的重写
return super.getSalary(month)+salary;
}
}
最后对上述进行测试
public class TextEmployee {
public static void main(String[] args) {
SalariedEmployee s1=new SalariedEmployee();//用new关键字实例化对象
s1.month=2;
s1.salary=1000;
System.out.println(s1.getSalary(s1.salary, 2));
HourlyEmployee s2=new HourlyEmployee();
s2.month=3;
s2.time=100;
s2.timesalary=10;
System.out.println(s2.getSalary(3));
SalesEmployee s3=new SalesEmployee();
s3.month=4;
s3.setMonthlysales(10000);//为私有变量赋初值,此处不可以像其他对象一样直接赋初值
s3.setRate(0.1);
System.out.println(s3.getSalary(4));
BasePlusSalesEmployee s4=new BasePlusSalesEmployee();
s4.month=5;
s4.setMonthlysales(10000);
s4.setRate(0.1);
s4.salary=100;
System.out.println(s4.getSalary(5));
}
}
程序运行结果
1100.0
1100.0
1100.0
1200.0