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?
awt. Button class implements the Serializable interface, so you can serialize a java. awt. Button object and store that serialized state in a file.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With