// ex 4 // ex 4c: A java.io,NotSerializableException is thrown when trying to serialize instances of classes which do not implement the Serializable interface // ex 4d: A NoClassDefFoundError is thrown import java.io.*; public class SerializableTester { public static void main(String[] args) throws IOException, ClassNotFoundException { Person p1 = new Person("Hans"); Person p2 = new Person("Palle"); Car c1 = new Car("green", p1); Car c2 = new Car("red", p2); // ex a ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("tmp") ); oos.writeObject(p1); oos.writeObject(p2); oos.close(); // print the persons and their cars ObjectInputStream ois = new ObjectInputStream( new FileInputStream("tmp") ); p1 = (Person) ois.readObject(); p2 = (Person) ois.readObject(); System.out.println(p1); System.out.println(p2); ois.close(); // ex b // change one of the objects new Car("purple", p1); // hans now has a new car // save and load the objects again oos = new ObjectOutputStream( new FileOutputStream("tmp2") ); oos.writeObject(p1); oos.writeObject(p2); oos.close(); ois = new ObjectInputStream( new FileInputStream("tmp2") ); System.out.println( ois.readObject() ); System.out.println( ois.readObject() ); ois.close(); } } class Car implements Serializable { Person owner; String color; Car(String color, Person owner) { this.owner = owner; this.color = color; owner.setCar(this); } public String toString() { return color + " car"; } } class Person implements Serializable { String name; Car car; Person(String name) { this.name = name; } void setCar(Car car) { this.car = car; } public String toString() { return name +"'s " + car; } }