编程教程
您现在的位置: 中国个人站长站 >> 网络编程 >> Javascript >> 教程正文 谈谈J2SE中的序列化(二)
推荐位

谈谈J2SE中的序列化(二)

中国个人站长站 Javascript 点击数: 更新时间:2007-7-28 12:39:53
        }

    }

}

 

运行结果如下:

supervalue: 100 sub: 200

可见子类成功的序列化/反序列化了。

 

怎管让子类实现序列化看起来是一件很简单的事情,但有的时候,往往我们不能够让父类实现Serializable接口,原因是有时候父类是抽象的(这并没有关系),并且父类不能够强制每个子类都拥有序列化的能力。换句话说父类设计的目的仅仅是为了被继承。

要为一个没有实现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;

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

 

我们将SuperC的Serializable接口去掉,而给SubC加上Serializable接口。运行后产生错误:

java.lang.Error: Unresolved compilation problem:

    Serializable cannot be resolved or is not a valid superinterface

    at Serial.SubC.<init>(SubC.java:15)

    at Serial.Test1.main(Test1.java:19)

Exception in thread "main"

    果真如docs中所说的一样,父类缺少无参构造函数是不行的。

上一页  [1] [2] [3] [4] [5] [6] [7] 下一页

教程录入:swh    责任编辑:swh 
个人站长站与你风雨同舟!
本站所提供的资源均来源于互联网,如有侵权行为,请与本站管理员联系,我们会第一时间删除!
·如果您发现《谈谈J2SE中的序列化(二)》文章有错误,也请通知我们修改!
联系邮箱chinageren#126.com,谢谢支持!
站内搜索:
广告服务 | 友情链接 | 联系我们 | 免责声明 | 用户留言 | 网站导航
版权所有:中国个人站长站 2007-2008 未经授权禁止复制或建立镜像 客服QQ号:112731235
copyright © 2007-2008 www.ChinaGeRen.com online services. all rights reserved. 苏ICP备05000059号