保存和重新加载Employee和Manager对象网络的代码(有些对象共享相同的表示秘书的雇员)。秘书对象在重新加载之后是唯一的。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
*
*/
/**
* @author Administrator 新浪微博:ouc大飞
*/
public class ObjectStreamTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee1 harry = new Employee1("Harry Hacker", 50000, 1989, 10, 1);
Manager carl = new Manager("Carl Cracker", 75000, 1987, 12, 15);
carl.setSecretary(harry);
Manager tonny = new Manager("Tony Tester", 4000, 1990, 3, 15);
tonny.setSecretary(harry);
Employee1[] staff = new Employee1[3];
staff[0] = carl;
staff[1] = harry;
staff[2] = tonny;
try {
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("D:\\ww.dat"));
out.writeObject(staff);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("D:\\ww.dat"));
Employee1[] newStaff=(Employee1[])in.readObject();
in.close();
newStaff[1].raiseSalary(10);
for(Employee1 e:newStaff)
System.out.println(e);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
class Employee1 implements Serializable {
public Employee1() {
}
public Employee1(String n, double s, int year, int month, int day) {
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public Date getHireDay() {
return hireDay;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString() {
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee1 {
public Manager(String n, double s, int year, int month, int day) {
super(n, s, year, month, day);
secretary = null;
}
public void setSecretary(Employee1 s) {
secretary = s;
}
public String toString() {
return super.toString() + "[secretary=" + secretary + "]";
}
private Employee1 secretary;
}