My question is: What is the best way to write the constructor of a Java class with fields that are initialized through stdin?
For example suppose that I have an Employee class that looks like:
Public class Employee {
private int empID;
private String empName;
private List<Role> empRoles;
{....}
}
I can write all the setters and getters for this class. Of course, the Role class will have its own file.
Also suppose that I make my setters for the first two fields as follows, in order to enable the end user to initialize the fields:
public void setEmpID() {
System.out.println("Please enter the employee ID");
Scanner s = new Scanner (System.in);
this.empID = s.nextInt();
public void setEmpName() {
System.out.println("Please enter the employee name");
Scanner s = new Scanner (System.in);
this.empName = s.next();
} }
then:
- Can I use such setters in a constructor that overrides the default constructor.
- Is this the best way to write such constructors?
-
Is it better to move the Scanner object I am creating in each setter to the constructor and make it as an argument for the setters (e.g:
public void setEmpName(Scanner s) { ... this.empName = s.next(); }
)?
As you can see, this may be a design question rather than just "coding".
Many thanks for your help.
Aucun commentaire:
Enregistrer un commentaire