An interviewer asked me this:
class Employee{
private string empname;
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
}
class EmpDetails{
private static Employee emp;
public static List fillData(){
emp=new Employee();
List l=new ArrayList();
System.out.println("static after new creation fillData"+System.identityHashCode(emp));
emp.setEmpname("suresh");
emp.setDesignation("Sr.Software Engineer");
l.add(emp);
emp=new Employee();
System.identityHashCode(emp);
System.out.println("static after new creation fillData"+System.identityHashCode(emp));
emp.setEmpname("Prasad");
emp.setDesignation("Software Engineer");
l.add(emp);
return l;
}
}
What happens if define below
private static Employee emp;
What is advantage with define static and non-static non access modifer with employee object?
If a field is defined static, then the value of that field is shared by all the instances of a that particular class. In your case how ever, that field is defined as private, which restricts instances of the class to access it outside the class. When your fill dataget() called it will create the list of Employee and static emp field will hold the value of the last emp(“Prasad”). If any other instance of class EmpDetails is created and you try to access emp without calling fillData, using some other method e.g. GetEmp(), then it will return the last value for emp which was set to “Prasad”.
With respect to design, this approach is not correct, as EmpDetails class will be pointing to one Employee due to static Employee object.