Java Serialization – Exemple avec Héritage
1. Classes initiales
class Person implements Serializable {
String name;
Person(String name) {
[Link] = name;
}
}
class Student extends Person {
String school;
public Student(String name, String school) {
super(name);
[Link] = school;
}
public String toString() {
return name + " " + school;
}
}
public class TestClass {
public static void main(String[] args) {
Person p = new Student("Bob Dylan", "NYU");
try (
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"));
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"));
) {
[Link](p);
[Link]();
[Link]((Student) [Link]());
} catch (Exception e) {
[Link]();
}
}
}
2. Problème
• Le code actuel ne fonctionne pas correctement si Student n’implémente pas Serializable
explicitement.
1
• Java exige :
• Si une superclasse est serializable, la sous-classe peut l’être automatiquement.
• Si une superclasse n’est pas serializable, elle doit avoir un constructeur sans arguments.
3. Solution
Faire que Student implémente Serializable :
class Student extends Person implements Serializable {
String school;
public Student(String name, String school) {
super(name);
[Link] = school;
}
public String toString() {
return name + " " + school;
}
}
4. Résultat attendu
Bob Dylan NYU
5. Règles importantes pour la sérialisation avec héritage
Cas Condition
Superclasse Serializable Sous-classe automatiquement sérialisable
Superclasse Non-Serializable Doit avoir constructeur sans argument
Champs de la sous-classe Doivent être serializable ou déclarés transient