Why static fields are not serialized

Static fields of a class are shared among objects of that class. Just imaging they would be serialized, what would happen if you have instantiated an object of a class containing an important static variable and that you would deserialize an object of the same class. The static field would be overwritten. Sometimes, however, you may want this type of behavior. The solution is simple: just customize serialization through the methods writeObject and readObject as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         Test t1 = new Test();
         t1.create();
 
         System.out.println("State of t1: " + t1);
 
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(t1);
         oos.flush();
 
         // make static variable count 0 to prove our point
         Test.count = 0;
 
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
         ObjectInputStream ois = new ObjectInputStream(bais);
         Test t2 = (Test) ois.readObject();
 
         System.out.println("State of t2: " + t2);  
      }
      catch(ClassNotFoundException e) {
         System.out.println(e); 
      }
      catch(IOException e) { 
         System.out.println(e); 
      }
   }
}
 
class Test implements Serializable {
   public int var = 0;
   public static int count = 0;
  
   Test() { }
 
   public void create() {
      var = 1;
      count++;
   }
 
   private void writeObject(ObjectOutputStream oos) throws IOException {
      oos.defaultWriteObject();
      // write static variable
      oos.writeInt(count);
   }
 
   private void readObject(ObjectInputStream ois) throws IOException, 
                                              ClassNotFoundException {
      ois.defaultReadObject();
      // read static variable
      count = ois.readInt();
   }
  
   public String toString() {
      return "var = " + var + "; count = " + count;
   }
}

outputs:

State of t1: var = 1; count = 1
State of t2: var = 1; count = 1