Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Java provides an interface as a means of achieving abstraction. It is a class blueprint that contains constants and abstract methods. The term "marker interface" refers to an interface that lacks methods, fields, and constants. So an empty interface is often called a marker interface in Java.
In this blog, we will discuss the marker interface in Java in detail and some examples of marker interfaces in Java.
What is a Marker Interface?
A marker interface, also called a tagging interface, is an interface that doesn't contain any methods or constants within it. Its purpose is to provide run-time type information about objects, which allows the compiler and JVM to have more information about the object.
Serializable, Cloneable, and Remote interfaces are some marker interfaces in Java. Each of these interfaces is empty.
Syntax of Marker Interface in Java
public interface Serializable {
// Rest of the code
}
You can also try this code with Online Java Compiler
In Java, we have two other alternatives for marker interface which can do the work of marker interface.
Internal Flags - These can be used in place of a marker interface to add special behavior to a class.
Annotations - By using annotations for a class, we can perform the same task as the marker interface.
Uses of Marker Interface
Metadata Conveyance: Marker interfaces convey metadata to the Java runtime and compilers without containing any methods or fields.
Property/Behavior Indication: They mark a class with a specific property or behavior.
Example - Serializable: Indicates that a class can be serialized, allowing its objects to be converted into a byte stream for saving or transferring.
Example - Cloneable: Signifies that a class permits cloning, enabling its objects to be copied.
Design Constraints Enforcement: Help enforce design constraints in a type-safe manner.
Functionality Enablement: Enable certain functionalities without modifying the class's structure.
Examples of Marker Interface in Java
In Java, there are some built-in marker interfaces that we can directly use instead of implementing them. We will see three of the most used marker interface in Java.
1. Cloneable Interface
It is a part of Java.lang package. A cloneable interface is used to make a copy or clone of an object with a different name. A class must implement the Cloneable interface in order to copy its objects. The method clone() of the object class is responsible for making the clone of that object. When calling the clone() method on a class that does not implement the Cloneable interface, a ClassNotSupportedException is raised.
Example
Java
Java
class Student implements Cloneable { int roll; String name; int marks;
// Constructor public Student(int roll, int marks, String name) { // Initializing data members this.roll = roll; this.marks = marks; this.name = name; }
// Function to print student record public void Student_record() { System.out.println("Student name: " + this.name); System.out.println("Student Roll no: " + this.roll); System.out.println("Student Marks: " + this.marks); }
public static void main(String[] args) throws CloneNotSupportedException { // Some random student Details String name = "ABC"; int roll = 10; int marks = 90;
// Creating first student object Student S1 = new Student(roll, marks, name); System.out.println("Student record of student S1: "); S1.Student_record(); System.out.println();
System.out.println("Student record of student S2: "); // Cloning objects of student S1 into student S2 using clone()method Student S2 = (Student)S1.clone(); S2.Student_record(); } }
You can also try this code with Online Java Compiler
In the above code of cloneable interface, In order to use cloneable interface, we first implemented it in the Student class. After creating the object S1 we used to clone() method to make another object S2 which will be a clone of object S1. Here we need to typecast the object returned by the clone() method into an object of the Student class.
2. Serializable Interface
Serialization is a method that lets you read an object state out of memory and write it to a file or database. In Short, Serialization transforms an object's state into a byte stream. Similarly, deserialization is the opposite of serialization, i.e., transforming byte stream into an object's state. The java.io package has a serializable interface. We can serialize or deserialize an object's state using a serializable interface.
Example
Java
Java
import java.io.*; class Student implements Serializable { int roll; String name; int marks;
// Constructor public Student(int roll, int marks, String name) { // Initializing data members this.roll = roll; this.marks = marks; this.name = name; }
public static void main(String[] args) throws ClassNotFoundException, IOException { // Some random student Details String name = "Lucky"; int roll = 10; int marks = 90;
// Creating an object of student class Student S1 = new Student(roll, marks, name);
/* Serialization Creating stream to write object */ FileOutputStream fout = new FileOutputStream("Student.txt"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(S1);
/* De-serialization Creating stream to read object */ FileInputStream fin = new FileInputStream("Student.txt"); ObjectInputStream oin = new ObjectInputStream(fin);
In the above code of serializable interface, We created a stream using FileInputStream to read the contents of object S1. These contents are copied to another object S2 using the readObject() method and typecasted into an object of the student class. After printing the details, both streams need to be closed using the close() method.
3. Remote Interface
A remote object is one that is stored on one computer but can be accessed from another computer. The java.rmi package contains a Remote interface. It is used with the remote method invocation(RMI). RMI is a technology that enables an object operating on one system (JVM) to access or invoke an object running on another. Any remote object is required to directly or indirectly implement this interface.
Example
import java.rmi.Remote;
import java.rmi.RemoteException;
// Creating a Remote class
public class Student implements Remote {
// Rest of the code
}
You can also try this code with Online Java Compiler
A custom marker interface is a Java interface which has no methods or constants. It is used to provide additional information about a class or object.
To use a custom marker interface, we need to create a class or object that implements the interface. We don't require to provide any implementation for the methods or constants in the interface
Here is an example of a custom marker interface:
Java
Java
interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("Drawing a circle."); } }
class Square implements Shape { public void draw() { System.out.println("Drawing a square."); } }
public class Main { public static void main(String[] args) { Shape circle = new Circle(); Shape square = new Square();
circle.draw(); square.draw(); } }
You can also try this code with Online Java Compiler
In the above code, we have the Shape interface with the draw() method. Two classes, Circle and Square implement the interface and provide their specific draw() method implementation. The main method creates instances of Circle and Square using the Shape interface reference and calls their draw() methods directly.
Output:
Drawing a circle.
Drawing a square.
You can also try this code with Online Java Compiler
The above code demonstrates the use of a custom marker interface to achieve polymorphism, where different classes share a common interface and can be used interchangeably to perform specific actions (draw() in this case) without the need to know their exact implementations.
Marker Interface Vs Annotations
Annotations in Java work the same as the marker interface. So what is the difference between both of them? - Answer is polymorphism. Whenever we implement a marker interface for a class, then automatically, all of its child classes implement it too. But this is not the behaviour with annotations. In annotations, we have to specifically write above the class classes about the implementation.
Example
Let's first create a class that implements serialization.
public class CodingNinjas implements Serializable {
// Rest of the code
}
You can also try this code with Online Java Compiler
Let's now create three child classes for this class.
// Creating first child class
public class blogWriter extends CodingNinjas {
// Rest of the code
}
// Creating second child class
public class blogReviewer extends CodingNInjas {
// Rest of the code
}
// Creating third child class
public class blogManager extents CodingNinjas {
// Rest of the code
}
You can also try this code with Online Java Compiler
Now, As the marker interfaces follow the principle of polymorphism, all the child classes of CodingNinjas will also implement the serializable implementation. But what if we want only the child class blogWriter to implement the serializable interface? - Here comes annotations into play.
If we want to make a child class implement a serializable interface, then we need to manually mention @SerializableAnnotation for that class only as shown below:
@Serializable
public class blogWriter extends CodingNinjas{}
// Don't mention for these classes
public class blogReviewer extends CodingNinjas{}
public class blogManager extends CodingNinjas{}
You can also try this code with Online Java Compiler
By this method, only the specified child class becomes serializable. But if you want all the child classes to implement the interface then this method becomes a hell of a work because we need to write the same statement repeatedly. So if you are smart and want to save time, then just use the marker interface :D.
Marker Interface Vs Typical Interface
Well, Ninjas, you must be thinking, why do we need a marker interface when we have our normal interfaces, right? - Well this is because the marker interface has something more up to its sleeves which a normal interface doesn’t have.
Example
Let us see it through the same example; we just need to make some changes shown below:
public interface CodingNinjas {
// Rest of the code
}
// Creating child interfaces
public interface blogWriter extends CodingNinjas{}
public interface blogReviewer extends CodingNinjas{}
public interface blogManager extends CodingNinjas{}
You can also try this code with Online Java Compiler
Suppose that we want to remove an employee from Coding Ninjas. For that, let’s create another class to do our job.
public class Remove_employee {
// Other methods here
public boolean Remove(Object object) {
if (object instanceof blogWriter) {
// Delete details of blogWriter
return true ;
}
// Return without any changes if condition is not satisfied
return false ;
}
}
You can also try this code with Online Java Compiler
This class will check if that object is an instance of blogWriter. If it is, then it will get removed else not. Now, this was possible because all the child classes were implementing the marker interface. But if we have a new position called blog leader with the instance given below:
public interface blogLeader {
// Rest of the code
}
You can also try this code with Online Java Compiler
Now, if we want the objects of some classes that have implemented this interface to be removed. Then it is not possible in a normal interface but possible in a marker interface. So if you want to do it in a normal interface, then we need to make some changes in Remove_employee class as shown below:
public class Remove_employee {
// Other methods here
public boolean Remove(Object object) {
if ( (object instanceof blogWriter) || (object instance of blogLeader)) {
// Delete details of blog writer or blog leader
return true ;
}
// Return without any changes if both the conditions are not satisfied
return false ;
}
}
You can also try this code with Online Java Compiler
Now, it seems to be good to write this way. But suppose there are a lot of other positions in the future, then every time we need to modify the class. Therefore using a marker interface, in this case, is a way better choice than a normal interface.
Frequently Asked Questions
What is an example of a marker interface in Java?
An example of a marker interface in Java is the Serializable interface. A class that implements the Serializable interface indicates that it can be serialized and deserialized.
Where we can use marker interface in Java?
We can use a marker interface in Java to indicate that a class can be serialized, to indicate a class can be clonable and to indicate a class can be remotely accessed.
What can we use instead of marker interface in Java?
We can use annotations instead of marker interfaces in Java. Annotations provide a more flexible and readable way to add metadata to classes, methods, or fields, and can be processed at runtime or compile time.
What is the difference between marker interface and normal interface?
A marker interface does not contain any methods and is used to convey metadata about a class, whereas a normal interface defines methods that a class must implement, specifying a contract for the class's behavior.
Conclusion
This article discusses the marker interface in Java, along with examples. We hope this blog has helped you enhance your knowledge of the marker interface in Java. If you want to learn more, then check out our articles.