Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Show how to customise serialization of a class with private writeObject and readObject methods, for example to validate fields after reading. What must the methods call?

We declare two private methods with exact signatures, private void writeObject(ObjectOutputStream out) throws IOException and private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, and the serialization machinery calls them instead of its default behaviour. Inside, we call out.defaultWriteObject() and in.defaultReadObject() first to handle the ordinary fields, then copy any mutable fields defensively, check the class's invariants and throw InvalidObjectException if they are broken. Marking both methods with @Serial lets the compiler check the signatures.

Why this question is asked

Default serialization copies field values blindly. That is fine until a class has rules, such as a minimum that must not exceed a maximum, or holds mutable objects that must not be shared, or contains derived state that should be rebuilt rather than saved. Because deserialization skips constructors, none of the constructor's checks run, and a corrupted or crafted stream can produce an object that the rest of the code assumes cannot exist. Interviewers ask this coding question to see whether we know the hook methods, their exact contract, and why validation in readObject matters. In this answer, we will recap why the hooks exist, write a class that customises both methods, see what each call does, add defensive copies, look at writing extra data, and use @Serial to catch mistakes.

1A Quick Recap: Why the Hooks Exist

When ObjectOutputStream writes a serializable object, it checks whether the class declares a private method called writeObject with the exact signature. If it does, it calls that method instead of writing the fields itself; ObjectInputStream does the same with readObject. The methods are private because they are an agreement between the class and the serialization machinery, not part of the class's API, and the machinery calls them by reflection for each class in the hierarchy.

The important point for reading is that the class's constructor never runs. So readObject is, in effect, a second constructor, and it needs the same checks the real constructor has.

2Writing the Two Methods

Here is a class with an invariant (min must not exceed max), a mutable field (a Date) and a derived transient field that we rebuild after reading.

Java
public final class TemperatureRange implements Serializable {
@Serial private static final long serialVersionUID = 1L;
private double min;
private double max;
private Date measuredAt; // mutable
private transient String label; // derived, not saved
public TemperatureRange(double min, double max, Date measuredAt) {
if (min > max) throw new IllegalArgumentException("min > max");
this.min = min;
this.max = max;
this.measuredAt = new Date(measuredAt.getTime());
this.label = min + ".." + max;
}
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // writes min, max, measuredAt
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // reads min, max, measuredAt
if (measuredAt == null) throw new InvalidObjectException("measuredAt is missing");
measuredAt = new Date(measuredAt.getTime()); // defensive copy before checking
if (min > max) throw new InvalidObjectException("min " + min + " > max " + max);
label = min + ".." + max; // rebuild the transient field
}
}

defaultWriteObject() writes all non-static, non-transient fields exactly as default serialization would, and defaultReadObject() reads them back into the fields. We call them first so the stream contains the normal fields in the normal layout; that also keeps the format compatible if we later add fields. Here writeObject does nothing extra, and we could leave it out, but declaring it makes the symmetry clear and gives us a place to add data later.

3Validating After Reading

After defaultReadObject() returns, the fields hold whatever the stream said. A crafted stream can contain min = 50 and max = 10, values our constructor would never allow. So readObject repeats the constructor's checks and throws InvalidObjectException, a subclass of IOException, when they fail.

Java
TemperatureRange r = roundTrip(new TemperatureRange(10, 25, new Date()));
System.out.println(r.label()); // 10.0..25.0: label rebuilt after reading
// The same bytes, edited so that min = 50.0 and max = 10.0:
readFrom(tamperedBytes);
// java.io.InvalidObjectException: min 50.0 > max 10.0
Step throughWhat readObject does, in order
  1. in.defaultReadObject()fields now hold the stream's values
  2. Required fields present?
    Yesgo onNothrow InvalidObjectException
  3. Copy mutable fieldsthe stream may share references with an attacker
  4. Invariants hold on the copies?
    Yesrebuild transient stateNothrow InvalidObjectException

4 steps in order. Play them, or step through them one at a time.

The reader gets an exception instead of a broken object, exactly as if a constructor had rejected the values. A useful habit is to put the checks in one private method that both the constructor and readObject call, so they cannot drift apart.

4Why Defensive Copies Come First

Serialization keeps shared references: if the stream refers to the same Date object twice, both references point to one object after reading. An attacker can build a stream that, besides our TemperatureRange, contains an extra back reference to the very Date object stored inside it. After deserialization, the attacker holds a reference to our private Date and can change it later, bypassing every check, which the constructor's copy normally prevents.

So readObject copies each mutable field into a new object that nobody else can reach. Notice the order: copy first, then validate the copy. If we validated first and copied afterwards, the value could change between the check and the copy. For immutable types such as Instant or String, no copy is needed, which is one more reason to prefer immutable field types in serializable classes.

5Writing Extra Data and Keeping the Order

writeObject can also write data that is not a field, for example the state of a non-serializable superclass, or a format version. Whatever we write after defaultWriteObject must be read back in the same order and with the matching methods.

Java
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(2); // our own format version
out.writeUTF(unit.name()); // unit is a field of a non-serializable superclass
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
int version = in.readInt(); // 2
unit = version >= 2 ? Unit.valueOf(in.readUTF()) : Unit.CELSIUS;
// ... defensive copies and validation as before
}

If the read order differs from the write order, we get corrupted values or an OptionalDataException, so the two methods should always be read side by side in review.

6Letting the Compiler Check the Signatures With @Serial

The hook methods are found by name and exact signature. A tiny mistake, making readObject public, misspelling it as readObjects, or forgetting the throws ClassNotFoundException part, means the method is silently ignored and default serialization runs instead. The @Serial annotation, added in Java 14, marks a member as part of the serialization mechanism. With javac's -Xlint:serial checks enabled, the compiler warns when an @Serial member does not have a valid serialization signature, turning a silent bug into a build warning, which we can make an error with -Werror.

One more limit: records ignore writeObject and readObject entirely. For a record, the place to validate is the compact constructor, which deserialization always calls.

7Follow-up questions

What is the difference between InvalidObjectException and throwing IllegalArgumentException?

readObject is declared to throw IOException and ClassNotFoundException, so InvalidObjectException, an IOException, fits the contract and reaches callers as a normal read failure. An unchecked exception would also stop the read, but callers handling stream errors would not expect it.

How do you validate a whole object graph rather than one object?

Call in.registerValidation(callback, priority) inside readObject. The callback runs after the whole graph has been read, so it can check relationships between objects that are not yet complete during the individual readObject calls.

What is readObjectNoData for?

It handles a stream written before our class was added as a superclass of the serialized class. The stream has no data for us, so readObjectNoData lets us set valid defaults instead of leaving fields at zero or null.

8Conclusion

In this answer, we wrote private writeObject and readObject methods with their exact signatures, called defaultWriteObject and defaultReadObject first for the ordinary fields, and used readObject as a second constructor: copy mutable fields defensively, validate the invariants on the copies, throw InvalidObjectException when they fail, and rebuild transient state. We also wrote extra data in a matching order and used @Serial so the compiler can check the signatures.

What to say in the interviewAbout 90 seconds aloud

Open with

I declare two private methods with exact signatures: private void writeObject taking an ObjectOutputStream and throwing IOException, and private void readObject taking an ObjectInputStream and throwing IOException and ClassNotFoundException.

Then, if they want more

Serialization finds them by reflection and calls them instead of the default behaviour. Inside writeObject I call out.defaultWriteObject first, which writes all the normal non-transient fields, and then anything extra, like a version number. Inside readObject I call in.defaultReadObject first, and after that I treat the method as a constructor, because deserialization never runs the real constructor.

So I make defensive copies of mutable fields like a Date, because a crafted stream can include a second reference to the same object and keep a handle on my internal state, then I check the invariants on the copies, for example that min is not greater than max, and throw InvalidObjectException if they fail.

Then I rebuild any transient derived fields. If I write extra data, I read it back in exactly the same order. I annotate both methods with @Serial, from Java 14, so that with the serial lint checks the compiler warns me if a signature is wrong, because a wrong signature is otherwise silently ignored.

And for records I do none of this: they ignore these methods, and validation goes in the compact constructor.

About this answer

Last updated
12 November 2026
Versions it names
Java 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to customise serialization of a class with private writeObject and readObject...": https://scrivio-interview-library.netlify.app/java/serialization/9a0d20f4a2/