当一个父类实现serializable接口后,他的子类都将自动的实现序列化。
以下验证了这一点:
| package serial; import java.io.serializable; public class superc implements serializable {//父类实现了序列化 int supervalue; public superc(int supervalue) { this.supervalue = supervalue; } public string tostring() { return "supervalue: "+supervalue; } } public class subc extends superc {//子类 int subvalue; public subc(int supervalue,int subvalue) { super(supervalue); this.subvalue=subvalue; } public string tostring() { return super.tostring()+" sub: "+subvalue; } } public class test1 { public static void main(string [] args){ subc subc=new subc(100,200); fileinputstream in=null; fileoutputstream out=null; objectinputstream oin=null; objectoutputstream oout=null; try { out = new fileoutputstream("test1.txt");//子类序列化 oout = new objectoutputstream(out); oout.writeobject(subc); oout.close(); oout=null; in = new fileinputstream("test1.txt"); oin = new objectinputstream(in); subc subc2=(subc)oin.readobject();//子类反序列化 system.out.println(subc2); } catch (exception ex){ ex.printstacktrace(); } finally{ …此处省略 } } } |
| supervalue: 100 sub: 200 |
| “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. ” |
| 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" |
| public abstract class superc { int supervalue; public superc(int supervalue) { this.supervalue = supervalue; } public superc(){}//增加一个无参的constructor public string tostring() { return "supervalue: "+supervalue; } } public class subc extends superc implements serializable { int subvalue; public subc(int supervalue,int subvalue) { super(supervalue); this.subvalue=subvalue; } public string tostring() { return super.tostring()+" sub: "+subvalue; } private void writeobject(java.io.objectoutputstream out) throws ioexception{ out.defaultwriteobject();//先序列化对象 out.writeint(supervalue);//再序列化父类的域 } private void readobject(java.io.objectinputstream in) throws ioexception, classnotfoundexception{ in.defaultreadobject();//先反序列化对象 supervalue=in.readint();//再反序列化父类的域 } } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器