Yes,
Of course you can define a constructor as private. Private
constructors prevents to directly instantiate this class from outside.
public class Employee { private String firstName, lastName; private Employee(){ } private Employee(String firstName, String lastName){ this.firstName = firstName; this.lastName = lastName; } static Employee getObject(String firstName, String lastName){ return new Employee(firstName, lastName); } String getFirstName(){ return firstName; } String getLastName(){ return lastName; } }
public class EmployeeTest { public static void main(String args[]){ Employee emp = Employee.getObject("abc", "def"); System.out.println(emp.getFirstName()); System.out.println(emp.getLastName()); } }
Output
abc def
Related
Links
No comments:
Post a Comment