title: Tricky situation with serializing and deserializing transient objects
body: <p>Here's my code:</p>
  
  <pre><code>class Collar {
    int size;
  }
  
  class Dog implements Serializable {
    int weight;
    transient Collar c;
  
    public Dog(int weight, int size) {
      this.weight = weight;
      c = new Collar();
      c.size = size;
    }
  
    public void writeObject(ObjectOutputStream os) throws Exception {
      os.defaultWriteObject();
      os.writeInt(c.size);
    }
  
    public void readObject(ObjectInputStream is) throws Exception {
      is.defaultReadObject();
      c = new Collar();
      c.size = is.readInt();
    }
  }
  
  public class test {
    public static final String FILE_REVISION = "$Revision$";
  
    public static void main(String ar[]) throws Exception {
      Dog dOut = new Dog(20, 2);
  
      System.out.println("DOut Weight: " + dOut.weight + " Size: " + dOut.c.size);
  
      FileOutputStream fo = new FileOutputStream("Dog.ser");
      ObjectOutputStream os = new ObjectOutputStream(fo);
      os.writeObject(dOut);
  
      FileInputStream fi = new FileInputStream("Dog.ser");
      ObjectInputStream is = new ObjectInputStream(fi);
      Dog dIn = (Dog) is.readObject();
  
      System.out.println("DIn Weight: " + dIn.weight + " Size: " + dIn.c.size);
    }
  }
  </code></pre>
  
  <p>and here's the output:</p>
  
  <pre><code>DOut Weight: 20 Size: 2
  Exception in thread "main" java.lang.NullPointerException
      at test.main(test.java:55)
  </code></pre>
  
  <p>Line 55 is the last line of code that has System.out.println()</p>
  
  <p>The program is able to get back the serializable object, which is Dog here.  However, its not able to create a new 'containment' object, Collar, when I'm reading back using custom readObject method.  Where am I going wrong?</p>
  
  <p>As you can see the output is NullPointerException in 'dIn.c.size' statement.  Even though I'm setting up c as a new object in custom readObject method, it's not working really.</p>