object serialization

java.io.Serializable

对象要输入输出,请用ObjectInputStream ObjectOutputStream
那么好吧 你的对象implements Serializable 先

为什么要对象序列化呢?下面的例子
每个对象在memory中都有自己的序列号,而不是内存地址,因为对象加载的时候,内存地址很可能会改变,而且在网络中的不同的计算机传递对象的时候,根据什么来标志对象呢,要用序列号,那么好吧,序列化先。

下例中的 harry在memory中只有一份,在a,b中怎么来表示他们都拥有harry呢?引用序列号啊


package xml;
import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import java.io.*;

public class ObjectStreamTest {
public static void main(String[] args){
Employee harry=new Employee("harry",2300,1919,1,1);
Manager a=new Manager("a",8800,1919,1,1);
a.setSecretary(harry);
Manager b=new Manager("b",8800,1919,1,1);
b.setSecretary(harry);

Employee[] staff=new Employee[3];
staff[0]=harry;
staff[1]=a;
staff[2]=b;

try{
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("ObjectStream.txt"));
out.writeObject(staff);
out.close();

ObjectInputStream in=new ObjectInputStream(new FileInputStream("ObjectStream.txt"));
Employee[] newStaff=(Employee[])in.readObject();
in.close();

for(Employee e:newStaff)
System.out.println(e);
}catch(Exception e){}
}
}
class Employee implements Serializable{
private String name;
private double salary;
private Date hireDay;

public Employee(){}
public Employee(String n,double s,int y,int m,int d){
this.name=n;
this.salary=s;
GregorianCalendar calendar=new GregorianCalendar(y,m-1,d);
this.hireDay=calendar.getTime();
}

public String getName(){
return this.name;
}
public double getSalary(){
return this.salary;
}
public Date getHireDay(){
return this.hireDay;
}

public String toString(){
return getClass().getName()+"[name="+name+",salary="+this.salary+",hireday="+this.hireDay+"]";
}
}

class Manager extends Employee{
private Employee secretary;

public Manager(String n,double s,int year,int month,int day){
super(n,s,year,month,day);
secretary=null;
}

public void setSecretary(Employee s){
this.secretary=s;
}

public String toString(){
return super.toString()+"[secretary="+secretary+"]";
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值