要求:定义员工类Employee, 包含姓名和工资, 包含姓名和月工资,计算年工资getAnnual的方法。普通员工和经理继承了员工类,经理类多了奖金bonus属性和管理mange方法,普通员工多了work方法。普通员工和经理需要重写计算工资getAnnual方法。
目录
1. Employee类
package org.example.poly_.polyparm;
import java.util.Objects;
/**
* author 大力pig
*/
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) && Objects.equals(salary, employee.salary);
}
@Override
public int hashCode() {
return Objects.hash(name, salary);
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary='" + salary + '\'' +
'}';
}
public double getAnnual(){
return 12 * salary;
}
}
2. Manger类
package org.example.poly_.polyparm;
import java.util.Objects;
/**
* author 大力pig
*/
public class Manger extends Employee{
private double bonus;
public Manger(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
Manger manger = (Manger) o;
return Double.compare(manger.bonus, bonus) == 0;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bonus);
}
@Override
public double getAnnual() {
return super.getAnnual() + getBonus();
}
public void mange(){
System.out.println("经理" + getName() + "在管理");
}
}
3. Worker类
package org.example.poly_.polyparm;
/**
* author 大力pig
*/
public class Worker extends Employee{
public Worker(String name, double salary) {
super(name, salary);
}
public void work(){
System.out.println("普通员工" +getName() + "正在工作");
}
@Override
public double getAnnual() {//普通员工没有项目奖金,只有工资。
return super.getAnnual();
}
}
4. Main测试类
package org.example.poly_.polyparm;
/**
*@author 大力pig
*/
public class PolyParm {
public static void main(String[] args) {
Worker tom = new Worker("tom", 2500);
Manger milan = new Manger("milan", 5000, 200000);
PolyParm polyParm = new PolyParm();
polyParm.showEmpAnnual(tom);
polyParm.showEmpAnnual(milan);
polyParm.testWork(tom);
polyParm.testWork(milan);
}
//该方法可以拿到任何员工的工资
public void showEmpAnnual(Employee e){
System.out.println(e.getAnnual());
}
//添加一个方法,如果是普通员工,则调用work方法,如果是经理,则调用mange方法
public void testWork(Employee e){
if (e instanceof Worker){
((Worker) e).work();
}else if(e instanceof Manger){
((Manger) e).mange();
}else {
System.out.println("类型错误");
}
}
}