Here's a real live example: decent appservers can temporarily store session data (specifically, the attributes of HttpSession
) on disk when the server has to be shut down or restarted, so that it can restore all session data on startup. In a clustered environment the appserver will also write session data to disk so that it can be shared among appservers in the cluster.
Writing Java objects (usually just javabeans) to disk require that they implements java.io.Serializable
(which is just a marker interface). Rougly said, with implementing the interface the developer gives JVM the permission to store this data on the disk file system. But that also imples that anything else outside the context can access this data.
If the class implementing serializable contains a field which you'd like not to be stored on the disk file system, for example private String password
(bad example, but it should give you the idea), then you can just declare it transient
to avoid its value being serialized to disk:
private transient String password;
You only have to live with the fact that it won't be restored with its original value after deserialization. You have to write additional logic to restore its value yourself. Fields marked static
will also not be serialized, but they usually already get initialized during loading of the class.
Hope this gives a clear picture.