title: Why is a serializable inner class not serializable?
body: <p>The following code:</p>
  
  <pre><code>public class TestInnerClass {
  
      public static void main(String[] args) throws IOException {
          new TestInnerClass().serializeInnerClass();
      }
  
      private void serializeInnerClass() throws IOException {
          File file = new File("test");
          InnerClass inner = new InnerClass();
          new ObjectOutputStream(new FileOutputStream(file)).writeObject(inner);
      }
  
      private class InnerClass implements Serializable {
  
          private static final long serialVersionUID = 1L;
  
      }
  
  }
  </code></pre>
  
  <p>throws the following exception:</p>
  
  <pre><code>Exception in thread "main" java.io.NotSerializableException: TestInnerClass
  </code></pre>
  
  <p>I guess the inner class has a <code>TestInnerClass.this</code> field that allows it private access to <code>TestInnerClass</code>'s fields and methods. Declaring the inner class static <a href="http://www.coderanch.com/t/268954/java-programmer-SCJP/certification/inner-classes-serialization" rel="noreferrer">solves it</a>, but what if <code>InnerClass</code> needs this access? Is there a way to serialize a non-static inner class without the enclosing class, e.g. by making the reference to the outer class <code>transient</code>?</p>
  
  <p>edit: for example, access to the outer class could be needed only before serialization. OK, the compiler cannot know that, but I thought that's why the <code>transient</code> keyword exists.</p>