java 某公司的人员分为员工和经理两种,但经理也属于员工中的一种,公司的人员都有自己的姓名和地址,员工和经理都有自己的工号、工资、工龄等属性,但经理不同员工的是,经理有自己在公司对应的级别。假设每次给员工涨工资一次能涨10,经理能涨20%。本案例要求利用多态实现给员工和经理涨工资。代码
时间: 2023-10-25 10:25:41 浏览: 156
以员工为编写一个程序,定义如下类:以员工为父类,该类包含员工的基本信息:姓名、年龄、部门。创建两个子类:经理类和工人类,输出经理和工人的工资。在父类中编写getSalary()方法,在子类中覆盖,实现多态。
5星 · 资源好评率100%
下面是一个简单的实现:
Person.java:
```java
public class Person {
private String name;
private String address;
public Person(String name, String address) {
this.name = name;
this.address = address;
}
public String getInfo() {
return "Name: " + name + ", Address: " + address;
}
}
```
Employee.java:
```java
public class Employee extends Person {
private int id;
private int salary;
private int years;
public Employee(String name, String address, int id, int salary, int years) {
super(name, address);
this.id = id;
this.salary = salary;
this.years = years;
}
public String getInfo() {
return super.getInfo() + ", ID: " + id + ", Salary: " + salary + ", Years: " + years;
}
public void raiseSalary() {
salary += 10;
}
}
```
Manager.java:
```java
public class Manager extends Employee {
private String level;
public Manager(String name, String address, int id, int salary, int years, String level) {
super(name, address, id, salary, years);
this.level = level;
}
public String getInfo() {
return super.getInfo() + ", Level: " + level;
}
public void raiseSalary() {
salary += salary * 0.2;
}
}
```
Main.java:
```java
public class Main {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Employee("Tom", "123 Main St", 1001, 30000, 5);
people[1] = new Manager("Jerry", "456 Elm St", 1002, 50000, 10, "Senior");
people[2] = new Employee("Mary", "789 Oak St", 1003, 40000, 7);
for (Person person : people) {
if (person instanceof Employee) {
((Employee) person).raiseSalary();
} else if (person instanceof Manager) {
((Manager) person).raiseSalary();
}
System.out.println(person.getInfo());
}
}
}
```
在这个例子中,Person类作为员工和经理的父类,Employee类作为员工的子类,Manager类作为经理的子类。在主函数中,我们首先创建了一个Person数组,包含了三个不同类型的人员对象。然后通过循环遍历该数组,根据对象类型分别对员工和经理进行涨工资的操作,实现了多态的效果。
阅读全文