Tuesday, 19 August 2014

Can a constructor be private in Java ?

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());
    }
}
                                                             Home

No comments:

Post a Comment