What are the conditions for Serializable?

1.1k views Asked by At

Suppose I have a java class, MyClass, that is not inherited from any class. MyClass implements Serializable.

Can MyClass be Serializable with no other conditions? Does it depend on what objects MyClass contain, and if these objects are Serializable themselves?

For example in the class below, if Mappedoodle2 does not implement Serializable, will I get an exception when Mappedoodle is serialized?

import java.io.Serializable;

public class Mappedoodle implements Serializable {
   private static final long serialVersionUID = -1760231235147491826L;
   private String text;
   private int value;
   private Mappedoodle2 mm = new Mappedoodle2();

   public Mappedoodle(String text, int value) {           
       this.text = text;
       this.value = value;
   }

   public String getText() {
       return text;
   }

   public int getValue() {
       return value;
   }

   @Override
   public String toString() {
       return text + ", " + value;
   }

}
2

There are 2 answers

0
riddle_me_this On

First, all classes technically extend from java.lang.Object, so even MyClass will inherit from it.

MyClass can implement Serializable just by implementing the interface, like any other interface. If a class contains properties of a class that implements Serializable, the parent class need not implement Serializable itself.

0
James Westman On

To serialize the object, I'm assuming you are using an ObjectOutputStream. Here's some relevant documentation: http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject(java.lang.Object)

That section describes the basics of how objects are written. The stream writes the following:

  • The class that the object is
  • The signature (public class Mappedoodle implements Serializable)
  • All fields that are neither transient nor static

Each field that is an object will also be written to the stream. This means that each field must implement Serializable. If it doesn't, you will get a NotSerializableException.

You have a couple of options for making this work:

  • Make Mappedoodle2 serializable
  • Make the field mm transient, which just means it won't be serialized.