Saturday, 29 May 2010

Example program for employee details by using Factory method

Example program on Factory method
//by using Static factory method and instance factory method
package com.raj;

public class Employee {
int empId;
String empName;
float empSalary;

//private zero argument constructor
private Employee()
{
System.out.println("Default constructor");
}
//static factory method
public static Employee createNewEmployee(int empId,String empName)
{
//use Class.forName ()
Employee emp=new Employee();
emp.empId=empId;
emp.empSalary=6000;//default salary of new employee
emp.empName=empName;
return(emp);
} //end of static factory method
//instance factory method
//To increment salary, we need existing employee object
public Employee incrementSalary(float hike)
{
Employee emp=new Employee();
emp.empSalary=this.empSalary*(1+hike);//20% hike
//copy all the necessary properties
emp.empId=this.empId;
emp.empName=this.empName;
return(emp);
}
public String toString()
{
return("EmpDetails="+empId+":"+empName+":"+empSalary);
}

} //end of Employee class

package com.raj;

public class TestClient {
public static void main(String args[]) throws Exception
{
Employee emp1=Employee.createNewEmployee(1001, "Rama");
//emp1 calls toString()method internally
System.out.println(emp1);

Employee emp2=emp1.incrementSalary(0.20f);
System.out.println("With Hike"+emp2);
}//main

}//end of TestClient class
/* output
 * Default constructor
EmpDetails=1001:Rama:6000.0
Default constructor
With HikeEmpDetails=1001:Rama:7200.0005

 */
*/
Factory Method

No comments:

Post a Comment