2-4 编程练习
来源:2-4 编程练习
刘徽
2023-04-29 18:29:00
public class Employee {
//根据需求完成Employee类的定义
int id;
String name;
double salary;
public Employee() {
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
public class EmployeeTest {
public static void main(String[] args) {
//定义ArrayList对象
ArrayList<Employee> employeeList = new ArrayList<Employee>();
//创建三个Employee类的对象
Employee e1 = new Employee("张三",5000.0);
Employee e2 = new Employee("李四",5500.0);
Employee e3 = new Employee("赵六",4000.0);
//添加员工信息到ArrayList中
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
//显示员工的姓名和薪资
System.out.println("员工姓名\t员工薪资");
for (Employee employee : employeeList){
System.out.println(employee.getName()+ "\t" +employee.getSalary());
}
}
}
运行结果:
1回答
同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。
另外建议同学养成属性封装的好习惯,即创建Java类时,尽量将属性使用private进行修饰。
祝学习愉快~
相似问题