Should added members be proteced or private?
Warren Levy
warrenl@cygnus.com
Sat Jul 29 23:13:00 GMT 2000
On 2000年7月28日, Tom Tromey wrote:
> Jeff> Should I keep everything that is not in the API spec as private,
> Jeff> or can I used friendly/default or protected as necessary? I
> Jeff> assume I should not add anything public to the class.
>> Definitely do not add new public or protected fields or methods.
>> If the class is serializable you might also consider making sure your
> implementation conforms to the serialization spec.
That's right, serialization is very sensitive on a couple levels.
For serializable classes, all non-static, non-transient fields are saved
off (in the default case)!
On top of that, ALL fields except 'private static' and 'private transient'
are used in the computation of the serialVersionUID (the checksum used in
versioning of classes). Thus for fields, if they're not in the JDK spec
you really should make them 'private transient' (or 'private static' if
appropriate) for total compatibility.
Regarding methods and constructors and the computation of the
serialVersionUID, all non-private methods and constructors are used in the
calculation, so here again it is important to make them private for
compatibility.
Note, that the JDK class doc has "Serialized Form" links from some classes
which describe some fields (and methods) necessary for serialization
compatibility. For more info see:
http://java.sun.com/products/jdk/1.2/docs/api/serialized-form.html
This is not the *only* way to maintain compatible classes from a
serialization standpoint, but it certainly is the easiest and most
obvious way (IMO).
If you're interested in the details, the spec and other doc can be found
at:
http://java.sun.com/products/jdk/1.2/docs/guide/serialization/
--warrenl
More information about the Java
mailing list