13

In "Layman's" terms I was wondering if someone could explain to me the significance and general importance of importing the Serializable class to implement the java.io.Serializable interface. asked from java student

java_threads
  • 131
  • 1
  • 1
  • 3

2 Answers2

14

java.io.Serializable is what is known as a "marker interface". The interface itself has no methods defined in it. So any class can easily implement this interface by simply implementing it:

 public class MyClass implements Serializable {
       public void aMethodForMyClass() { }

       // not implementing any specific java.io.Serializable methods because
       // the interface has no methods to implement.
 }

It is a "marker" interface because by implementing this interface you are telling the Java serializer that it is OK to serialize objects of this type. If your class does not implement this interface, the serializer will refuse to serialize any objects of that type.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • 1
    It also means you promise all variables making up an object of this class is either serializable too, or that you implement the needed code for handling them anyway. – JenEriC Apr 02 '11 at 10:10
  • Is this something that happens at compile time or in the JVM. In other words if I don't implement Serializable and try to serialize a class will I encounter compiler or run time errors? – BrightIntelDusk Jan 28 '15 at 03:26
4

All you need to know about Java Serialization can be found in the Java Serialization Specification

The Java Serialization FAQ also contains the answer to your question.

Specifically the first question seems to be the same you are asking:

Why must classes be marked serializable in order to be written to an ObjectOutputStream?

I hope that helps!

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205