Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who actually implements serializable methods?

I've been learning how to use Serializable.

I know if I create a class 'A' with different variables who implements Serializable and I add Serializable to my class, it's also Serializable.

But, who is actually implementing those two methods to serialize? Does Object take care of everything or different classes overloads them when necessary?

like image 923
Macarse Avatar asked Jun 09 '09 15:06

Macarse


People also ask

Which class should implement Serializable?

awt. Button class implements the Serializable interface, so you can serialize a java. awt. Button object and store that serialized state in a file.

How is serialization implemented in Java?

Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces. The Serializable interface must be implemented by the class whose object needs to be persisted.

How is Serializable interface implemented?

The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods.

Why do we implements Serializable?

Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class. Serializable classes are useful when you want to persist instances of them or send them over a wire.


1 Answers

The serialization is actually implemented in java.io.ObjectOutputStream (and java.io.ObjectInputStream) and some of its helper classes. In many cases, this built-in support is sufficient, and the developer simply needs to implement the marker interface Serializable. This interface is called a "marker" because it doesn't declare any methods, and thus doesn't require any special API on implementation classes.

A programmer can add or replace default serialization mechanism with their own methods if needed. For example, if some additional initialization is required after deserializing an object, a method can be added with the following signature:

private void readObject(java.io.ObjectInputStream s)
               throws java.io.IOException, java.lang.ClassNotFoundException

For total control over serialization and deserialization, implement java.io.Externalizable instead of Serializable.

There are many other extension points in Java serialization, if needed. The serialization specification is an authoritative and complete source for learning about all of them.

like image 132
erickson Avatar answered Oct 13 '22 12:10

erickson