java职员薪水代码
时间: 2024-11-04 22:09:18 浏览: 5
在Java中,员工薪资通常会被设计成一个简单的类,比如`Employee`和它的派生类`SalaryWorker`, `HourlyWorker`等。这里有一个基础的例子:
```java
// 定义一个抽象的员工类
abstract class Employee {
protected String name;
public Employee(String name) {
this.name = name;
}
// 抽象方法获取基本薪资
abstract double getBaseSalary();
}
// 实体类 - 固定月薪员工
class SalaryWorker extends Employee {
private double monthlySalary;
public SalaryWorker(String name, double monthlySalary) {
super(name);
this.monthlySalary = monthlySalary;
}
@Override
public double getBaseSalary() {
return monthlySalary;
}
}
// 实体类 - 按小时计酬员工
class HourlyWorker extends Employee {
private double hourlyRate;
public HourlyWorker(String name, double hourlyRate) {
super(name);
this.hourlyRate = hourlyRate;
}
// 假设一周工作40小时
@Override
public double getBaseSalary() {
return hourlyRate * 40;
}
}
// 主程序中演示多态
public class Main {
public static void main(String[] args) {
Employee emp1 = new SalaryWorker("张三", 8000);
Employee emp2 = new HourlyWorker("李四", 25);
System.out.println("工资员张三的月薪资: " + emp1.getBaseSalary());
System.out.println("小时工李四的日薪资(按周计算): " + emp2.getBaseSalary());
}
}
```
在这个例子中,`Employee`是父类,而`SalaryWorker`和`HourlyWorker`是子类。`getBaseSalary()`是一个抽象方法,在每个子类中都有具体的实现,体现了多态性。
阅读全文