如何在给定问题中将输入添加到 HashSet。我主要是想使用Manager类中的addEmployee、removeEmployee、printEmployee方法,但是不知道在main方法中要写什么,以便调用Manager类的addEmployee、removeEmployee、printEmployee方法
public class EmployeeTest
{
public static void main(String[] args)
{
Manager mgr = new Manager(207, "Barbara Johnson", "054-12-2367", 109_501.36, "US Marketing");
Employee e=new Employee(127, "Kyle Jenner", "023-42-5368", 123_243.90); // newly edited
mgr.addEmployee(e); //newly edited
mgr.printEmployee(e); //newly edited
printEmployee(mgr);
}
public static void printEmployee(Employee emp)
{
System.out.println();
System.out.println("Employee id: " + emp.getEmpId());
System.out.println("Employee name: " + emp.getName());
System.out.println("Employee Soc Sec #: " + emp.getSsn());
System.out.println("Employee salary: " + NumberFormat.getCurrencyInstance().format((double) emp.getSalary()));
}
}
public class Employee
{
private int Id;
private String name;
private String ssn;
private double salary;
public Employee(int Id, String name, String ssn, double salary)
{
this.Id = Id;
this.name = name;
this.ssn = ssn;
this.salary = salary;
}
public int getEmpId()
{
return Id;
}
public String getName()
{
return name;
}
public String getSsn()
{
return ssn;
}
public double getSalary()
{
return salary;
}
public void setName(String name)
{
if (name != null && !name.equals(""))
{
this.name = name;
}
}
public void raiseSalary(double increase)
{
if (increase > 0)
{
salary += increase;
}
}
}
public class Manager extends Employee
{
private String dept;
public Manager(int Id, String name, String ssn, double salary, String dept)
{
super(Id, name, ssn, salary);
this.dept = dept;
}
**private Set<Employee> staff=new HashSet<>();** //This is where I need help
**public void addEmployee(Employee e)** //This is where I need help
{
staff.add(e);
}
**public void removeEmployee(Employee e)** //This is where I need help
{
staff.remove(e);
}
**public void printEmployee(Employee e)** //This is where I need help
{
for (Employee emp: staff)
{
System.out.println("Name : "+getName()+" "+"ID : "+getEmpId());
}
}
public String getDeptName()
{
return dept;
}
}
程序输出
姓名:芭芭拉·约翰逊 ID:207//所需输出:- 姓名:凯尔·詹纳 ID:127
员工 ID:207
员工姓名:芭芭拉·约翰逊
员工社团编号:054-12-2367
员工工资:109,501.36卢比
在 Manager 上测试 raiseSalary 和 setName:
员工 ID:207
员工姓名:Barbara Johnson-Smythe
员工社团编号:054-12-2367
员工工资:119,501.36卢比
最佳答案
由于 printEmployee()
中 emp 的静态类型是 Employee
,因此您只能使用 Employee
中定义的方法(或定义并在 Manager
中覆盖)。
由于 printEmployee()
是在 Manager
中定义的,因此只能在声明为 Manager
关于java - Java中的方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33157777/