Why does the check of gender and employee number have to exist in the constructo
ID: 662358 • Letter: W
Question
Why does the check of gender and employee number have to exist in the constructor in this code? Why can't it just exist in the Set-method?
package employee;
import java.util.Scanner;
public class Employee extends Object
{Scanner input = new Scanner(System.in);
private String firstName;
private String lastName;
private char middleInitial;
private boolean fulltime;
private char gender;
private int employeeNum;
public Employee(String fn, String ln, char m, char g, int en, boolean ft)
{
firstName = fn;
lastName = ln;
middleInitial = m;
fulltime = ft;
if (g=='M' || g=='F'){
gender=g;
}
else
gender='F';
if(en < 10000 || en > 99999){
System.out.println("Invalid Employee Number, please re-enter");
this.employeeNum = input.nextInt();
}
else
this.employeeNum=en;
}
public void setFirstName(String fn)
{
firstName=fn;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String ln)
{
lastName = ln;
}
public String getLastName()
{
return lastName;
}
public void setMiddleInitial(char m)
{
middleInitial = m;
}
public char getMiddleInitial()
{
return middleInitial;
}
public void setGender(char g)
{
if (g=='M' || g=='F'){
gender=g;
}
else
gender='F';
}
public char getGender()
{
return gender;
}
public void setemployeeNum(int en)
{
if(en < 10000 || en > 99999){
System.out.println("Invalid Employee Number, please re-enter");
this.employeeNum = input.nextInt();
}
else
this.employeeNum=en;
}
public int getemployeeNum()
{
return employeeNum;
}
@Override
public boolean equals(Object e2)
{
if(this.employeeNum == ((Employee)e2).employeeNum)
{
return true;
}
else
{
return false;
}
}
@Override
public String toString()
{
return employeeNum + " " + lastName + ", " + firstName+" " + middleInitial + "."+" "+"Gender: "+ gender +" "+ "Status: "+ fulltime + " ";
}
}//End of class
Explanation / Answer
The check of gender and employee number have to exist in the constructor in this code because when an instance of the constructor is created the values of the object parameters are initialized. If the check of gender and employee is not done during the initialization then it might happen that incorrect values will reside in the object parameters. This might lead to problems until the error in the values is realised and the set method is called to correctly reset the values.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.