Marker Interface
It is an empty interface having no fields and methods inside it. Implementation of these interfaces will give a special definition to a class. Serializable and Clonnable interface are the example of marker interface. Cloneable interface belongs to java.lang.Cloneable and and serializable interface belongs to java.io.Serializable.
Syntax:
Public interface {
// having no fields and methods
}
Cloneable:
Cloning is similar to making a copy of an object. Below is the Employee class example where it has two fields with name and age stored in emp1 object. The clone() method will help us to make a copy of emp1 to emp2 with all field values.
Example :
OUTPUT:
Note:Accessing clone() method without implementing cloneable interface will throw CloneNotSupportedException exception
Serializable:
Serialization in java can be achieved by implementing Serializable interface.
Serialization allows us to serialize the object or write the state of object as it is into byte streams. The reverse of the serialization is deserialization where byte stream converts back to object with the same state what we serialized.
For serialization java uses writeObject() and for deserialization it is readObject().
Declaring a variable as transient inside a class will not allow to serialize or write the object into byte stream.
Example :
Below Employee class example is serializing the object state to byte stream using writeObject() method and for deserialization it is using readObject().
The point to be noted here for both the name and age variable values. After deserialization name is printing Test as value and age is printing default value as 0. After declaring a variable as transient inside a class will not allow to serialize or write the object into byte stream. While serialization it only serialized name field and ignore age variable as it is declared as transient.
OUTPUT:
Note :Accessing readObject() and wirteObject() methods without implementing Serializable interface will throw NotSerializableException exception.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.