java 继承 序列化_java 序列化之当序列化遭遇继承

当一个父类实现Serializable接口后,他的子类都将自动的实现序列化。

public class SerializableEr implements Serializable{

/**

*

*/

private static final long serialVersionUID = 1L;

// public SerializableEr(){};

}

public class Serial extends SerializableEr{

int id;

String name;

public Serial(int id, String name) {

this.id = id;

this.name = name;

}

public String toString() {

return "DATA: " + id + " " +name;

}

public static void main(String[] args) {

Serial serial=new Serial(1,"4234");

System.out.println("object serial:"+serial);

try{

FileOutputStream fos=new FileOutputStream("serialTest.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(serial);

oos.flush();

oos.close();

}catch(Exception e){

System.out.println("Exception:"+e);

}

}

}

运行结果如下:

object serial:DATA: 1 4234

要为一个没有实现Serializable接口的父类,编写一个能够序列化的子类是一件很麻烦的事情。java docs中提到:

“To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. ”

也就是说,要为一个没有实现Serializable接口的父类,编写一个能够序列化的子类要做两件事情:

其一、父类要有一个无参的constructor;

其二、子类要负责序列化(反序列化)父类的域。

public class SerializableEr{

/**

*

*/

private static final long serialVersionUID = 1L;

// public SerializableEr(){};

}

public class Serial extends SerializableEr implements Serializable{

int id;

String name;

public Serial(int id, String name) {

this.id = id;

this.name = name;

}

public String toString() {

return "DATA: " + id + " " +name;

}

public static void main(String[] args) {

Serial serial=new Serial(1,"4234");

System.out.println("object serial:"+serial);

try{

FileOutputStream fos=new FileOutputStream("serialTest.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(serial);

oos.flush();

oos.close();

}catch(Exception e){

System.out.println("Exception:"+e);

}

}

}

总结:

为一个实现Serializable接口的父类,编写一个能够序列化的子类 子类将自动的实现序列化

为一个没有实现Serializable接口的父类,编写一个能够序列化的子类 ,只要父类实现了序列化的接口,或者,子类实现了序列化的接口。就可以序列化

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-04-28 14:06

浏览 6591

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值