How does `private void readObject(ObjectInputStream stream)` return an object in custom serialization in Java?

I’m reading about custom serialization in Java, where you provide the following two methods inside the class that you want to serialize:

private void writeObject(ObjectOutputStream oos)
private void readObject(ObjectInputStream ois)

For example:

public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private transient Address address;
    private Person person;

    // setters and getters

    private void writeObject(ObjectOutputStream oos) 
      throws IOException {
        oos.defaultWriteObject();
        oos.writeObject(address.getHouseNumber());
    }

    private void readObject(ObjectInputStream ois) 
      throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        Integer houseNumber = (Integer) ois.readObject();
        Address a = new Address();
        a.setHouseNumber(houseNumber);
        this.setAddress(a);
    }
}

When you want to deserialize the serialized object of the class Employee as follows:

Employee e2 = (Employee) objectInputStream.readObject();

the Java virtual machine will call the readObject(ObjectInputStream ois) method defined in the class Employee instead of the readObject() of the ObjectInputStream class (source). However, the former method doesn’t return anything (void), unlike the latter method which returns an Object type (which should be casted).

So, how do we still get the Employee object from the above custom deserialization process?

Answer

You will not get any additional object as a result of this method – the readObject method is not static and to run this you need to have instance (let say of Employee class) and – it’s your object.

Take a look at the example from this tutorial – what you are doing there is actually setting fields of this object

private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException 
{       
    firstName = aInputStream.readUTF();
    lastName = aInputStream.readUTF();
    accountNumber = aInputStream.readInt();
    dateOpened = new Date(aInputStream.readLong());
}