Walking the Class Hierarchy

When an object is serialized, the highest serializable class in its derivation hierarchy is located and serialized first. Then the hierarchy is walked, with each subclass being serialized in turn. In order to illustrate this, let’s create an example with a three-level class hierarchy. Class C is a subclass of class B, which is a subclass of class A. Since class A implements java.io.Serializable, all of its subclasses are considered serializable as well. Again, this is due to the fact that all of its data members can be serialized. Each class implements the writeObject() and readObject() methods.

class A implements java.io.Serializable { protected int a; private void writeObject(ObjectOutputStream stream) throws java.io.IOException { System.out.println("writeObject called for class A"); stream.defaultWriteObject(); } private void readObject(ObjectInputStream stream) throws java.io.IOException { System.out.println("readObject called for class A"); try { stream.defaultReadObject(); } catch (ClassNotFoundException e) { throw new IOException(); } } public A() { } } class B extends A { protected int b; private void writeObject(ObjectOutputStream stream) throws java.io.IOException { System.out.println("writeObject called for class B"); stream.defaultWriteObject(); } private void readObject(ObjectInputStream stream) throws java.io.IOException { System.out.println("readObject called for class B"); try { stream.defaultReadObject(); } catch (ClassNotFoundException ...

Get Developing Java Beans now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.