父类没有实现Serializable接口时,没有无参的构造方法,类实现了Serializable接口,这时是可以将子类序列化,但反序列化是会报错的。
但如果父类有无参的构造方法,这时反序列化可以成功,且父类的成员变量的值为默认值,即便是子类实例化时赋值了。
当父类实现Serializable接口,此时无论写不写的构造方法也可以反序列化成功,且变量值为子类实例化时赋的值。
1 package serialize; 2 3 import java.io.Serializable; 4 5 public class Ser implements Serializable { 6 public String ser; 7 8 // public Ser() { 9 // } 10 11 public Ser(String ser) { 12 this.ser = ser; 13 } 14 }
1 package serialize; 2 3 import java.io.*; 4 5 public class SerializeDemo extends Ser implements Serializable { 6 7 String serialize; 8 9 // public SerializeDemo() { 10 // } 11 12 public SerializeDemo(String ser) { 13 super(ser); 14 } 15 16 public SerializeDemo(String ser, String serialize) { 17 super(ser); 18 this.serialize = serialize; 19 } 20 21 @Override 22 public String toString() { 23 return "SerializeDemo{" + 24 "serialize='" + serialize + '\'' + 25 ", ser='" + ser + '\'' + 26 '}'; 27 } 28 29 public static void main(String[] args) { 30 try { 31 new ObjectOutputStream(new FileOutputStream("src//serialize//Serialize2.txt")).writeObject(new SerializeDemo("ser","Serializable")); 32 SerializeDemo serializeDemo = (SerializeDemo) new ObjectInputStream(new FileInputStream("src//serialize//Serialize2.txt")).readObject(); 33 /** 34 *java.io.InvalidClassException: serialize.SerializeDemo; no valid constructor 35 * at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:150) 36 * at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:790) 37 * at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2001) 38 * at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535) 39 * at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422) 40 * at serialize.SerializeDemo.main(SerializeDemo.java:32) 41 * 42 * 父类没有实现Serializable接口 43 */ 44 System.out.println(serializeDemo); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } catch (ClassNotFoundException e) { 48 e.printStackTrace(); 49 } 50 } 51 }