Why are readObject and writeObject private, and why would I write transient variables explicitly?

前端 未结 6 1604
孤城傲影
孤城傲影 2020-12-02 12:47

I am reading the chapter on Serialization in Effective Java.

  1. Who calls the readObject() and writeObject()? Why are these methods declared private ?

6条回答
  •  庸人自扰
    2020-12-02 12:57

    Apart from should not be used by wrong parties, here is another reason for the privacy of these methods:

    We don't want these methods to be overridden by subclasses. Instead, each class can have its own writeObject method, and the serialization engine will call all of them one after the other. This is only possible with private methods (these are not overridden). (The same is valid for readObject.)

    (Note that this only applies to superclasses which themselves implement Serializable.)

    This way, subclasses and superclasses can evolve independently, and still stay compatible to stored objects from older versions.

提交回复
热议问题