What is Marker Interface in Java?


1. What is marker interface?

By usage, a marker interface does not contain any methods or variables. It is completely empty interface and for this reason also known as empty interface.

See these two marker interface definitions in Java API.

ima

java.lang.Cloneable and java.io.Serializable are two marker interfaces often used. See the output screen. No methods available, just open brace and close brace of the interface.

2. What is the use of marker interface in Java?
3. What marker interface can do?

a) When the marker interface does not have any methods to override by subclasses, then what is the use of marker interfaces in Java. It is question aked by everyone and also a favorite question in interviews for freshers.

b) When an object is created in Java, Java creates in such way that it can have sufficient capability to be used by the Programmer to call variables, methods and constructors. Java achieves encapsulation through objects. It is the default nature or behaviour for an object.

c) If the Programmer would like to give special processing capabilities to an object, he can inform so to the JVM through marker interfaces. If informed, JVM process the object in a different way so that the object can have special nature (apart default). For example,

public class Student implements Cloneable
{
  public static void main(String args[])
  {
    Student std1 = new Student();
  }
}

Now the Student object std1 comes with a special capability of cloning. When Cloneable is implemented by Student, the JVM tags the std1 to treat the object differently. For this reason, marker interface is also known as tag interface.

See this also.

public class Student implements Serializable
{
  public static void main(String args[])
  {
    Student std1 = new Student();
  }
}

Now the Student object std1 is serialized, and now can be written to a file and when required can be read back.

1. A program on Cloneable is available at Cloning – Duplicating an Object.
2. A program on Serializable is available at Java Serialization Example.
3. Complete table of marker interfaces available in Java is given at Java Made Clear: List of 7 Marker interfaces

View All for Java Differences on 90 Topics

Leave a Comment

Your email address will not be published.