Reputation: 145
So I'm stuck on some homework trying to create an instance of the Employee class from my class called records.
public class Employee implements Comparable<Employee>
{
/* instance variables */
private String Name;
private String employeeNumber;
/**
* Constructor for Employee
*/
public Employee(String employNum)
{
super();
this.employeeNumber = employNum;
}
Next I need to create a Record class that will create a HashSet of Employees details, this is where I need help.
public class Records
{
private HashSet employeeSet;
public Records()
{
Set<Employee> employeeSet = new HashSet<Employee>();
}
Then I want it to have a method for adding a new employee and then putting their records in the set.
public enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}
I can't get that last bit to create a new employee, it doesn't come out with an error and it compiles correctly. Just no new employee. *Adding the employeeSet.add(newEmp); caused a compiler warning and that method won't run due to a NullPointerException, probably because the employee isn't actually created.
For more info, when I create an employee the name should come out as "null" if only an employee number is entered but I still need to store that information.
Edited to update information. There is more detail for the Employee class which I have left out, I'm only supposed to be creating the Records class.
Last update, thank you for the help. After reading the replies this is what I got to work for me.
public class Records
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Records()
{
}
public void enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}
Upvotes: 1
Views: 16505
Reputation: 1776
Heres the new solution based on what you are looking for in the comments
public class Record
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Record()
{
newEmployee("1");
newEmployee("2");
newEmployee("3");
}
public void newEmployee(String employNumber)
{
Employee newEmp = new Employee(employNumber);
employeeSet.add(newEmp);
}
}
The method that you created was never called on... So an employee was never created. Therefore, by calling on the newEmployee method in the Record Constructor, a new employee is created
Upvotes: 4