import java.io.*; import java.awt.Rectangle; public class Transient extends Rectangle { // a field marked transient because it does not need serializing // this can be calculate from width, height protected transient int surfaceArea; //------------------------------------------------------------------- // main() entry point //------------------------------------------------------------------- public static void main (String[] args) { Object anObject; anObject = new Transient(10,33); System.out.println("Original object : " + anObject); saveObject(anObject, "trans.ser"); anObject = null; // loose original object anObject = (Transient) loadObject("trans.ser"); System.out.println("Restored object : " + anObject); } //------------------------------------------------------------------- // Transient constructor //------------------------------------------------------------------- public Transient(int width, int height) { super(width, height); this.surfaceArea = width*height; } //------------------------------------------------------------------- // utility function to save an object to a file //------------------------------------------------------------------- public static void saveObject(Object x, String filename) { FileOutputStream file; ObjectOutputStream freezer; // freeze x into an external file try { file = new FileOutputStream(filename); freezer = new ObjectOutputStream(file); freezer.writeObject( x ); freezer.close(); } catch (IOException noIO) { System.out.println("IO error occurred: " + noIO); } } //------------------------------------------------------------------- // utility function to load an object from a file //------------------------------------------------------------------- public static Object loadObject(String filename) { Object x = null; FileInputStream file; ObjectInputStream defreezer; // load first object contained in external file try { file = new FileInputStream(filename); defreezer= new ObjectInputStream(file); x = defreezer.readObject(); defreezer.close(); } catch (IOException noIO) { System.out.println("IO error occurred: " + noIO); } catch ( ClassNotFoundException unknownClass ) { System.out.println("Serialized object is of unknown type: " + unknownClass); } return x; } //------------------------------------------------------------------- // custom toString() for our Transient class //------------------------------------------------------------------- public String toString() { return super.toString()+" area="+ surfaceArea; } } // End of Class Transient