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接口的父类,编写一个能够序列化的子类 ,只要父类实现了序列化的接口,或者,子类实现了序列化的接口。就可以序列化