Friday, January 10, 2020

What are Marker Interfaces in Java?

Marker interfaces in java are interfaces with no members declared in them. They are just an empty interfaces used to mark or identify a special operation. For example, Cloneable interface is used to mark cloning operation and Serializable interface is used to mark serialization and deserialization of an object. Marker interfaces give instructions to JVM that classes implementing them will have special behavior and must be handled with care.
Marker interfaces don’t provide any functionality. In earlier versions of Java (Before Java 5), marker interfaces are used to provide metadata to the readers. With the introduction of annotations from Java 5, annotations are used more instead of marker interfaces to provide metadata. But, still many use marker interfaces to mark the special behavior of a class.
Java’s built-in Marker Interfaces:
These are some built-in marker interfaces in java which are used to mark some special behavior of a class.

1) java.lang.Cloneable Interface :
This interface is used to mark the cloning operation. An object of a class which implements Cloneable interface is eligible for field-by-field copying of an object.

2) java.io.Serializable Interface :
This interface is used to mark serialization and deserialization of an object. Serialization is a process in which an object state is read from memory and written into a file or a database. Deserialization is a process in which an object state is read from a file or a database and written back into memory. Any class which wants its object to be eligible for serialization and deserialization must implement Serializable interface.

3) java.util.EventListener :
This is also a marker interface which must be extended by all event listener interfaces.

4) java.rmi.Remote :
This is also a marker interface which is used to mark the invocation of a method remotely. Only methods of those classes which implement Remote interface are eligible for invocation by non-local virtual machine.

User Defined Marker Interfaces:
You can define your own marker interfaces to indicate about any special behavior. Below is such an example. In this example, Cash and Cheque are two marker interfaces which are used to indicate whether payment is done by cash or cheque.

interface Cash
{

}

interface Cheque
{

}

class PaymentOne implements Cash
{
    static void paymentByCash()
    {
        System.out.println("Payment is done by cash");
    }
}

class PaymentTwo implements Cheque
{
    static void paymentByCheque()
    {
        System.out.println("Payment is done by checque");
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        PaymentOne.paymentByCash();
        PaymentTwo.paymentByCheque();
    }
}


1 comment: