自学打卡 Java之对象序列化

对象序列化
在这里插入图片描述例8-6

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()方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值