You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.6 KiB

public class Employee { // 1. 定义私有属性 private String id; private String name; private String department; private double salary;

// 最低工资标准,设为常量
private static final double MIN_SALARY = 2000.0;

/**
 * 2. 提供必要的构造方法
 * 这里提供一个全参构造方法
 */
public Employee(String id, String name, String department, double salary) {
    this.id = id;
    this.name = name;
    this.department = department;
    // 使用 setSalary 方法来确保初始工资符合标准
    this.setSalary(salary);
}

// 3. 提供合理的 getter 和 setter 方法

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDepartment() {
    return department;
}

public void setDepartment(String department) {
    this.department = department;
}

public double getSalary() {
    return salary;
}

/**
 * 在 setSalary 中检查工资必须大于等于最低工资标准
 */
public void setSalary(double salary) {
    if (salary >= MIN_SALARY) {
        this.salary = salary;
    } else {
        System.out.println("工资 " + salary + " 低于最低标准 " + MIN_SALARY + ",已自动设置为最低标准。");
        this.salary = MIN_SALARY;
    }
}

/**
 * 4. 添加一个 raiseSalary 方法,按照百分比增加工资
 * percent 为 5 表示增加 5%
 */
public void raiseSalary(double percent) {
    if (percent < 0) {
        System.out.println("增长率不能为负数,增长无效。");
        return;
    }
    double raiseAmount = this.salary * (percent / 100.0);
    this.salary += raiseAmount;
    // 确保增加后仍不低于最低工资
    if (this.salary < MIN_SALARY) {
        this.salary = MIN_SALARY;
    }
    System.out.println("工资已按 " + percent + "% 的比例增长。");
}

/**
 * 为了方便打印对象信息,重写 toString 方法
 */
@Override
public String toString() {
    return "Employee{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", department='" + department + '\'' +
            ", salary=" + salary +
            '}';
}

}