Video in progress
What is the Serializable interface, and why does it have no methods at all?
Serializable is a marker interface: it tells the JVM "this object can be turned into bytes". ObjectOutputStream checks for this marker and throws NotSerializableException if it is missing.
📖 Answer
It needs no methods because the JVM does the work itself: it reads all the fields through reflection and writes them out as bytes.
record Point(int x, int y) implements Serializable {}
try (var out = new ObjectOutputStream(new FileOutputStream("p.bin"))) {
out.writeObject(new Point(3, 4));
}
try (var in = new ObjectInputStream(new FileInputStream("p.bin"))) {
Point p = (Point) in.readObject();
}
Important: the fields have to be serializable too. If the class has a Connection field that is not Serializable, the whole object cannot be written.
In practice Java serialization is rarely used today: the format is understood only by Java, it is hard to version, and it has security problems. Between services you usually use JSON or Protobuf. But in an interview they expect you to know the basics.
Sign up to mark studied questions and save your progress.