对象序列化
package practice;
import java.io.*;
import java.util.Date;
class employee implements Serializable{ //Serialzable是一个接口
private String name; //姓名
private double salary; //薪水
private Date hireDate; //雇佣日期
public employee (String n,double s,Date d) {
name =n;
salary =s;
hireDate=d;
}
public employee() {};
public void raiseSalary(double percent) { //涨薪水
salary*=1+percent/100;
}
public int hireYear() { //获取雇员年份
return hireDate.getYear();
}
public String getInfo() { //获取雇员信息
return name+"\t"+salary+"\t"+hireYear();
}
}
class manager extends employee{
private String secretaryName; //增加的实例变量secretaryName
public manager(String n ,double s,Date d) {
super(n,s,d);
secretaryName="";
}
public manager() {};
public void raiseSalary(double percent) {
Date today=new Date(2004,1,12);
double honus=0.5*(today.getYear()-hireYear());
super.raiseSalary(honus+percent);
}
public void setSecretaryName(String n) {
secretaryName=n;
}
public String getSecretaryName() {
return secretaryName;
}
public String getInfo() {
//覆盖父类中的方法
return super.getInfo()+"\t"+secretaryName;
}
}
public class Chapter8 {
public static void main(String []args){
employee staff[]=new employee[3];
staff[0]=new employee("John",1000,new Date(2010,10,1)); //雇员
staff[2]=new employee("Tony",1000,new Date(2010,4,26)); //雇员
manager m=new manager("Smith",1500,new Date(2010,6,12)); //经理
staff[1]=m;
m.setSecretaryName("Anna"); //设置经理的秘书名字
try { //创建序列化对象文件
FileOutputStream ostream=new FileOutputStream("test.dat");
ObjectOutputStream out=new ObjectOutputStream(ostream);
out.writeObject(staff);
out.close();
//从对象文件中读取数据
FileInputStream istream=new FileInputStream("test.dat");
ObjectInputStream in=new ObjectInputStream(istream);
employee newStaff[]=(employee[])in.readObject(); //读取对象
for(int i=0;i<newStaff.length;++i) {
newStaff[i].raiseSalary(50); //工资增加百分之50
}
for(int i=0;i<newStaff.length;++i) {
System.out.println(newStaff[i].getInfo());
}
}catch(Exception e) {
System.out.println("Exception:"+e);
System.exit(0);
}
}
}
【解析】程序中的employee newStaff[]=(employee[])in.reafObject()语句,之所以采用类型强制转换,因为readObject()方法返回值是Object()类型,必须将其转换为employee的数组类型。在输出结果的第二行,不但输出了Smith经理的信息,同事也输出了其秘书的姓名,这是因为newStaff[1]调用了manager类中的getInfo()方法,而new/staff[0]和newStaff[2]调用了employee类中的getInfo()方法。