Create an employee object having properties name, date of birth, department, designation and salary. Let the employee class have appropriate getter/setters methods for accessing these properties. Initialize these properties through the setter methods. Store this object into a file "OutObject.txt". Read the same object from the same file and display its properties through getter methods.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class Main
{
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Anne");
e.setDateOfBirth("12/09/1999");
e.setDepartment("Computer Science");
e.setDesignation("Lecturer");
e.setSalary(20000);
FileOutputStream f1 = new FileOutputStream("OutObject.txt");
ObjectOutputStream f2 = new ObjectOutputStream(f1);
f2.writeObject(e);
FileInputStream f3 = new FileInputStream("OutObject.txt");
ObjectInputStream f4 = new ObjectInputStream(f3);
Employee e2 = (Employee) f4.readObject();
System.out.println("Name: " + e2.getName());
System.out.println("Date of Birth: " + e2.getDateOfBirth());
System.out.println("Department: " + e2.getDepartment());
System.out.println("Designation: " + e2.getDesignation());
System.out.println("Salary: " + e2.getSalary());
f1.close();
f2.close();
f3.close();
f4.close();
}
}
class Employee{
private String name;
private String date_of_birth;
private String department;
private String designation;
private double salary;
public void setName(String n){
name=n;
}
public void setDateOfBirth(String d){
date_of_birth=d;
}
public void setDepartment(String dp){
department=dp;
}
public void setDesignation(String ds){
designation=ds;
}
public void setSalary(double s){
salary=s;
}
public String getName(){
return name;
}
public String getDateOfBirth(){
return date_of_birth;
}
public String getDepartment(){
return department;
}
public String getDesignation(){
return designation;
}
public double getSalary(){
return salary;
}
}
Comments
Leave a comment