Marker interfaces in Java are interface that does not contain methods, fields, and constants.
Basically, an Empty interface is known as a Marker interface.
A marker interface called ThreadSafe and a class implementing this marker interface give a thread-safe guarantee, and any modification should not violate that.
Purpose Of Marker Interface
The purpose of the marker interface is to provide run-time type information about an object.
If we have information about the class and we have to tell that information to the compiler, in that case, we use a marker interface.
After introducing Annotation on Java5, Annotation is a better choice than the marker interface.
In Built Marker Interface
In Java, there are some marker interfaces that already define in SDK.
Some of them are:
- Cloneable Interface
- Serializable Interface
- Remote Interface
Cloneable Interface
A cloneable interface is present in java.lang package. There is a method clone() in Object class.
clone() method is used for object cloning.
Object cloning refers to the creation of an exact copy of an object.
It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
We need to implement the cloneable interface in the class if we want to clone the object of that class.
1 2 3 |
protected Object clone() throws CloneNotSupportedException { throw new RuntimeException("Stub!"); } |
If we do not implement the Cloneable interface in the class and invoke the clone() method, it throws the CloneNotSupportedException.
Serializable Interface
The serializable interface is present in the java.io package. If we want to make the class serializable, we must implement the Serializable interface. If a class implements the Serializable interface, we can serialize or deserialize the state of an object of that class.
Serialization is the process of converting a data object into a series of bytes that saves the state of the object in an easily transmittable form.
1 2 3 4 5 |
package java.io; public interface Serializable { } |
Remote interface
The remote interface is present in java.rmi package. A remote object is an object which is stored at one machine and accessed from another machine.
We must implement the Remote interface if we want to make an object as remote.
1 2 3 4 5 |
package java.rmi; public interface Remote { } |
Custom Marker Interface
Java also allows us to make custom marker interfaces as per our requirements.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
interface Light{ //marker interface } class Sun implements Light { static void sunLight() { System.out.println("Sun light"); } } class CustomInterface { public static void main(String[] args) { Sun.sunLight(); } } |
Output: Sun light
Hope, this post will give an idea about Marker interface in java
Thank you !!