Java中定义一个员工类Employee,使用ArrayList对员工信息进行添加和显示。可以包含以下属性和方法: 属性: 姓名(name) 年龄(age) 性别(gender) 工号(id) 薪水(salary) 方法: 构造方法:可以传入姓名、年龄、性别、工号和薪水,初始化对象 getter和setter方法:用于获取和设置对象的属性值 toString方法:返回对象的字符串表示,可以输出对象的属性值
时间: 2023-04-02 16:00:42 浏览: 191
可以使用以下代码实现:
```
import java.util.ArrayList;
public class Employee {
private String name;
private int age;
private String gender;
private String id;
private double salary;
public Employee(String name, int age, String gender, String id, double salary) {
this.name = name;
this.age = age;
this.gender = gender;
this.id = id;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",性别:" + gender + ",工号:" + id + ",薪水:" + salary;
}
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("张三", 25, "男", "001", 500));
employees.add(new Employee("李四", 30, "女", "002", 600));
employees.add(new Employee("王五", 28, "男", "003", 550));
for (Employee employee : employees) {
System.out.println(employee.toString());
}
}
}
```
这个程序定义了一个员工类Employee,包含姓名、年龄、性别、工号和薪水等属性,以及构造方法、getter和setter方法、toString方法等方法。使用ArrayList对员工信息进行添加和显示。
在main方法中,创建了三个员工对象,并将它们添加到ArrayList中。然后使用for循环遍历ArrayList,输出每个员工对象的属性值。
阅读全文