To keep it simple:
You need or want to use public void setEmployeeId(String id) and its a basic requirement.
But if so, the idea of having such a method means that the class Employee should have any logic of id generation, instead by declaring such a method you say to the programmer that will use the Employee class: "Look, this class doesn't have an id, but you can create it and set".
If these are your intentions, then extract the logic of the id generation outside the employee class and use the "pure" setter:
main:
String id = generateId(...) // in this method there will be all the code with Random
Employee emp = new Employee();
emp.setId(id);
.....
class Employee {
private String id;
public void setId(String id) {this.id = id;}
}
Otherwise, if you do think that the Employee should generate an id by its own, you don't need a setter. In this case you can either call the generation code in constructor (not really recommended, but will work) or create an "init" method that will set the initial state of id to the employee object. In this case, whoever creates an Employee, will have to call this method:
public class Employee {
private String employeeId;
public class Employee(...) {...}
public void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Then in the main:
main:
Employee e = new Employee();
e.init(); // otherwise id won't be generated
This is not really convenient because whoever uses creates the Employee object will have to call init on it. In this case you might consider a factory method:
public class Employee {
private final String name;
private String empId;
private Employee(String name) {
this.name = name;
}
public static Employee create(String name) {
Employee emp = new Employee(name);
emp.init();
}
private void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Notice that the constructor is private now, which means that the only way to create Employee from main is using the create method. The init method also went private:
main:
Employee emp = Employee.create("John");
// the id is created - no need to remember to call "init" like in the previous example
privateand call it from your constructor. Remove the parameter.initEmployeeIDor something like that. It is not a setter.