需求

编写一个Employee类,声明方法为抽象类,包含:name、id、salary三个属性。提供必要的构造器和抽象方法:work()。对于Manager类来说,他既是员工,还具有奖金(bonnus)的属性。请使用继承的思想,设计CommonEmployee类和Manager类,要求类中提供必要的方法进行属性访问,实现work()。【继承+抽象】

实现

image.png

Employee

  1. package test;
  2. abstract public class Employee {
  3. private String name;
  4. private int id;
  5. private double salary;
  6. public Employee(String name, int id, double salary) {
  7. this.name = name;
  8. this.id = id;
  9. this.salary = salary;
  10. }
  11. //将work做成一个抽象方法
  12. public abstract void work();
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public int getId() {
  20. return id;
  21. }
  22. public void setId(int id) {
  23. this.id = id;
  24. }
  25. public double getSalary() {
  26. return salary;
  27. }
  28. public void setSalary(double salary) {
  29. this.salary = salary;
  30. }
  31. }

Manager

  1. package test;
  2. public class Manager extends Employee {
  3. private double bonus;
  4. public Manager(String name, int id, double salary) {
  5. super(name, id, salary);
  6. }
  7. public double getBonus() {
  8. return bonus;
  9. }
  10. public void setBonus(double bonus) {
  11. this.bonus = bonus;
  12. }
  13. @Override
  14. public void work() {
  15. System.out.println("经理 " + getName() + " 工作中...");
  16. }
  17. }

CommonEmployee

  1. package test;
  2. public class CommonEmployee extends Employee{
  3. public CommonEmployee(String name, int id, double salary) {
  4. super(name, id, salary);
  5. }
  6. @Override
  7. public void work() {
  8. System.out.println("普通员工 " + getName() + " 工作中...");
  9. }
  10. }

Main

  1. package test;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Manager wty2002 = new Manager("WTY2002", 1, 500000);
  5. wty2002.setBonus(1000);
  6. wty2002.work();
  7. CommonEmployee tom = new CommonEmployee("Tom", 2, 2000);
  8. tom.work();
  9. }
  10. }

image.png