类设计基础-------雇员工资统计
两类雇员,一种是合同雇员,他们的每月工资基本是固定的;而另一类是计时雇员,他们的薪水则与其工作了多少小时来计算。在每月发放工资前,公司的会计会求出所有员工的工资总额,然后到银行取出对应的数额准备发放工资。
设计系统,求每月员工的工资总和。
本题中雇员分为合同雇员和即时雇员。首先要找出他们的相同的地方:名字,取得工资;不同的是小时工有工时,合同工为每月的固定工资,二者在计算工资总和方式也不一样。
把共性的东西放在抽象类里,分别定义合同工类和计时工类从抽象类里继承。
基类 雇员类
package com.xzy;/** * 基类 雇员类 * @author xizhenyin * */public abstract class Employee { protected String name; public abstract int getSalary(); }
合同工类:
package com.xzy;/** * 合同工类 * @author xizhenyin * */public class ContractEmployee extends Employee{ private int salary; public ContractEmployee(String name,int salary){ this.name=name; this.salary = salary; } @Overridepublic int getSalary() {// TODO Auto-generated method stubreturn salary;} public String toString(){return "正式工"+" "+name +" "+ getSalary();}}
计时工类:
package com.xzy;/** * 小时工类 * @author xizhenyin * */public class HourEmployee extends Employee{ private static final int each = 30; //每小时工资 private int hours; public HourEmployee(String name,int hours){ this.name=name; this.hours = hours; }@Overridepublic int getSalary() {// TODO Auto-generated method stubreturn each*hours;} public String toString(){return "小时工"+" "+name +" "+ getSalary();}}
统计类:
package com.xzy;import java.util.ArrayList;import java.util.List;/** * * @author xizhenyin * */public class Caculator { List<Employee> emps ; public Caculator(){ emps = new ArrayList<Employee>(); } public void addEmployees(Employee em){ emps.add(em); } //计算总工资 public int sumSalary(){ int sum=0; for(Employee e:emps){ sum = sum + e.getSalary(); } return sum; } public void printInfo(){ for(Employee e:emps){ System.out.println(e); } } public static void main(String[] args) {Caculator ca = new Caculator();//加入正式工ca.addEmployees(new ContractEmployee("Jack",1200));ca.addEmployees(new ContractEmployee("Dawi",2000));ca.addEmployees(new ContractEmployee("Lily",2455));ca.addEmployees(new ContractEmployee("Lucy",2200));ca.addEmployees(new ContractEmployee("Miil",2500));ca.addEmployees(new ContractEmployee("Mydi",2400));//加入小时工ca.addEmployees(new HourEmployee("Bill",4));ca.addEmployees(new HourEmployee("Milu",6));ca.addEmployees(new HourEmployee("Cidy",3));ca.addEmployees(new HourEmployee("Honey",2));ca.addEmployees(new HourEmployee("Pipo",3));ca.printInfo();System.out.println();System.out.println("合计"+ca.sumSalary());}}
运行结果:
正式工 Jack 1200
正式工 Dawi 2000
正式工 Lily 2455
正式工 Lucy 2200
正式工 Miil 2500
正式工 Mydi 2400
小时工 Bill 120
小时工 Milu 180
小时工 Cidy 90
小时工 Honey 60
小时工 Pipo 90
合计13295
两个类ContractEmployee和HourEmployee都有自己工资计算方法,但必须实现父类规定实现的getSalary函数,这使得变化隐藏在接口背后,一方面便于修改而适于变化,另一方面也使外界计算工资总额的代码得以简化。