Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Marker Interface?
2.1.
Syntax of Marker Interface in Java
2.2.
Alternatives of Marker Interface in Java
3.
Examples of Marker Interface in Java
3.1.
1. Cloneable Interface
3.2.
2. Serializable Interface 
3.3.
3. Remote Interface
4.
Custom Marker Interface
5.
Marker Interface Vs Annotations
5.1.
Example
6.
Marker Interface Vs Typical Interface
6.1.
Example
7.
Frequently Asked Questions
7.1.
What is an example of a marker interface in Java? 
7.2.
Where we can use marker interface in Java?
7.3.
What is marker interface in Java interview questions?
7.4.
What are the types of marker interface in Java?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Marker Interface in Java

Author Gaurav Gandhi
1 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

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.

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
}

Alternatives of Marker Interface in Java

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.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

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();
    }
}


Output 

Cloneable interface output

Explanation

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

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);

        // Type-casting
        Student S2 = (Student)oin.readObject(); 

        // Printing details of cloned object
        System.out.println("Student Name: " + S2.name);
        System.out.println("Student Roll: " + S2.roll);
        System.out.println("Student Marks: " + S2.marks);

        // Closing the streams
        oout.close();
        oin.close();
    }
}


Output 

Serializable interface output

Explanation

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
}

Custom Marker Interface

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:

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();
    }
}

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.


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
}

 

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
}


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{}


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{}


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 ;
	}
}


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
}


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 ;
	}
}


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 is marker interface in Java interview questions?

Marker interface in Java interview questions typically asks to identify marker interfaces and explain how they are used in Java programming language.

What are the types of marker interface in Java?

There are two types of marker interfaces in Java that are Standard marker interfaces and Custom marker interfaces. The Standard marker interfaces are defined in the Java API, while the custom marker interfaces are created by developers.

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.

And many more on our platform Coding Ninjas Studio.

Happy Learning!

Previous article
Callable Interface in Java
Next article
Difference between Comparable and Comparator
Live masterclass