I am reading the serialization chapter in Effective Java. I am trying to understand the paragraph below, which is found in the book.
If you implement a class with instance fields that is serializable and extendable,there is a caution you should be aware of. If the class has invariants that would be violated if its instance fields were initialized to their default values (zero for integral types, false for boolean, and null for object reference types), you must add this readObjectNoData method to the class:
// readObjectNoData for stateful extendable serializable classes
private void readObjectNoData() throws InvalidObjectException {
throw new InvalidObjectException("Stream data required");
}
I am not sure what that statement means.
To test this, I created a class called Person (both serializable and extendable)
class Person implements Serializable {
private String name;
private int age;
Person() {
this("default", 1);
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
– and a class: Employee, which extends it.
class Employee extends Person {
String address;
public Employee() {
super();
address = "default_address";
}
public Employee(String name, int age, String address) {
super(name, age);
this.address = address;
}
}
Are there any invariants in the Person class I created? When will they be violated? I copy-pasted the code for the readObjectData()
method in the Employee class, but it never got called. When will the readObject()
method be called? Am I missing something?