继承类的自定义序列化

时间:2014-08-12 23:58:08

标签: java

如果要为派生类编写自定义序列化方法, 我是否必须再次读写基类字段?

A implements Serializable
{
   field1,
   field2 etc

      private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException
    {
      // read in field1
      //read in field2
    }

     private void writeObject(ObjectOutputStream outputStream) throws IOException
    {
       // write field1 to output stream
      //write field 2 to output stream
      }
}

Class B extends A
{
  field 3

      private void writeObject(ObjectOutputStream outputStream) throws IOException
    {
       //TODO : should contain only field 3 or field1,field2 and field 3?
    }

}

2 个答案:

答案 0 :(得分:2)

如果您在类型B的对象上调用writeObject,它将不会隐式调用A类中的writeObject方法。您必须使用super.writeObject(outStream)自行调用它,否则您可以在子方法本身中设置所有三个字段。简而言之,B中的writeObject函数应该包含你的所有三个字段。

答案 1 :(得分:1)

如果要覆盖该方法,则需要重新实现父类所做的所有操作。

只要在派生类中创建一个与父类具有相同签名的方法,它就会被覆盖,而父方法不再用于B类对象。

根据您的使用情况,您可能需要考虑使用abstract类。

相关问题