Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Marker Interface in Java with Examples

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

Get ready to explore the fascinating world of marker interfaces in Java! In the Java language, an interface is a reference type similar to a class that can contain only constants, method signatures, default methods, static methods, and nested types. It is essentially a contract that defines a set of methods without providing an implementation for those methods. In this article, we will explore the concept of marker Interfaces and understand their significance in Java programming.

What is a Marker Interface?

Marker interfaces are interfaces that do not have fields, methods, or constants. In other words, a marker or tag interface is an empty interface. The marker interface provides information about an object’s run-time type. Marker interfaces are also known as tag interfaces. They don’t provide any methods or constants to implement, but instead, they serve as a marker for a class.

 

The interface for a marker must be empty, but the declaration is the same as for an interface in Java.

Syntax of Marker Interface in Java

Here is the syntax of the Marker Interface in Java

 

public class MyClass implements MarkerInterfaceName { // Class Implementation }

 

Also Read: Hierarchical Inheritance in Java

JDK Marker Interfaces

In Java language, There are many built-in marker interfaces such as Serializable, Cloneable, and Remote

  • Cloneable Interface: This interface is present in java.lang.package. There is method clone() in the Object() class.  This class implements a Cloneable interface, indicating that it is legal for the clone() method to make a field for the field

copy of instances of that class. The ‘Cloneable’ interface does not contain any methods. It’s simply a marker interface to denote that a class is eligible for cloning 

 

The following program demonstrates the Cloneable Interface.

 

Program

 

class MyClass implements Cloneable { private int value; public MyClass(int value) { this.value = value; } public void setValue(int value) { this.value = value; } public int getValue() { return value; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class InterfaceExample { public static void main(String[] args) { MyClass obj1 = new MyClass(343); try { MyClass obj2 = (MyClass) obj1.clone(); System.out.println(“Original value: “ + obj1.getValue()); System.out.println(“Cloned value: “ + obj2.getValue()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }

 

Output

 

Original value: 343 Cloned value: 343

 

  • Serializable interface: This interface is present in the java.io package and is used to make an object eligible for saving its state into a file. It means its instance can be converted into a stream of bytes that can be saved to a file or sent over a network. This process is called serialization.

 

The following program Demonstrates the Serializable. This example creates two files xyz.txt file in your current working directory.

 

            Program

 

// Java Serializable Example in Programming import java.io.*; class Box implements Serializable { String name ; int number ; // A class constructor public Box(String name,int number) { this.name = name ; this.number = number ; } } public class SerializableExample{ public static void main(String[] args) throws IOException, ClassNotFoundException { Box ob = new Box(“Harry Potter”,20); FileOutputStream fos = new FileOutputStream(“xyz.txt”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ob); FileInputStream fis = new FileInputStream(“xyz.txt”); ObjectInputStream ois = new ObjectInputStream(fis); Box ob2 = (Box)ois.readObject(); System.out.println(ob2.name+” “+ob2.number); oos.close(); ois.close(); } }

 

Output

 

Harry Potter 20

 

  • Remote Interface: This interface is present in the Java.rmi package. A ‘remote interface’ typically refers to an interface intended for use in remote method invocation(RMI). This method of an object running in another JVM (Java Virtual Machine). It is possibly a different physical machine.
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Custom Marker Interface

In this section, we will create our own custom marker interface in Java using the example below. In this example, we have 2 classes: teachers and Students. We classify the objects of these 2 classes in 2 different lists using the marker interface.

 

The following program demonstrates the Custom Marker interface

 

Program

 

import java.util.*; interface StudentMarkerInterface { } class Teacher implements StudentMarkerInterface { int teacher_id; String name; Teacher(int teacher_id, String name) { this.teacher_id = teacher_id; this.name = name; } public String toString() { return “[ID: “ + teacher_id + “, Name: “ + name + “] “; } } class Student { int student_id; String name; public Student(int student_id, String name) { this.student_id = student_id; this.name = name; } public String toString(){ return “[ID: “ + student_id + “, Name: “ + name + “] “; } } class CustomMarkerInterface { static List<Teacher> teacherlist = new ArrayList<>(); static List<Student> studentlist = new ArrayList<>(); public static boolean save(Object object) { if (object instanceof StudentMarkerInterface) { teacherlist.add((Teacher)object) ; } else { studentlist.add((Student) object); } return true; } public static void main(String args[]) { Teacher ob = new Teacher(1, “Katrina Kaif”); save(ob) ; Teacher ob2 = new Teacher(2, “Sonam”); save(ob2) ; Student ob3 = new Student(4, “Sonali”); save(ob3) ; Student ob4 = new Student(5, “Aditi”); save(ob4); System.out.println(“Teacher List” + teacherlist); System.out.println(“Student List” + studentlist); } }

 

Output

 

Teacher List[[ID: 1, Name: Katrina Kaif] , [ID: 2, Name: Sonam] ] Student List[[ID: 4, Name: Sonali]] , [ID: 5, Name: Aditi] ]<strong> </strong>

 

Also Read: What is Palindrome Number in Java?

Marker Interface vs Annotations

The following table differentiates the Marker Interface and Annotation in Java language:

 

Feature Marker Interface Annotations
Definition Interfaces without methods serving as markers Declarations that can be applied to Java elements
Usage Denote participation in certain functionalities. Carry metadata, specify attributes, and retention
Examples Serializable’, ‘Cloneable’, ‘Remote’ etc ‘@Override’, ‘@Deprected’, @SuppressingWarnings, etc.
Flexibility Limited, cannot carry additional features Highly flexible, support for attributes.
Retention Not applicable, always available at runtime Can specify retention policies (source, class, runtime)
Reflection Not required for basic usage It is often used for reflection for runtime introspection.
Complexity Simple to define and use in Java It is more complex due to attributes and policies

Marker Interfaces vs Typical Interfaces

In this section, we will discuss the Marker Interfaces and Typical Interfaces differences. The following table demonstrates the Marker Interface and Typical Interface:

 

Feature Marker Interface Typical Interfaces
Definition Interfaces without methods Interface with one or more abstract methods
Purpose It indicates certain characteristics or behaviors It defines a contract for classes to implement methods
Usage Provide metadata about classes at compile or runtime It specifies a set of methods that classes must implement
Examples ‘Serializable’, ‘Cloneable’ etc ‘Comparable’, ‘Runnable’, and ‘Iterable’ etc.
Methods No methods only used for marking Contains one or more abstract methods to implement
Implementation Implementing classes inherit marker characteristics Implementing classes must provide a method of implementation
Flexibility Limited, cannot carry additional behavior Highly flexible, can define any required behavior
Extensibility Cannot add methods or modify behavior Highly extensible methods or modified behavior

Conclusion

In this article, we have learned about the Marker interfaces in Java that serve as mechanisms to provide metadata about classes, indicating certain characteristics or behaviors without requiring the implementation of any methods. We also learned about some examples of Marker Interfaces, such as “Serializable,” “Cloneable,” and “Remote.” By implementing these interfaces, classes denote their ability to be serialized, cloned, or used in remote method invocation, respectively.

 

FAQs
A marker interface in Java does not declare any methods. Its sole purpose is to mark or identify a class for some special treatment or behavior.
The runnable interface is not a maker interface because it has the public void run() method declared inside it. A marker interface example is Serializable, where the class implements can be used with ObjectOutputStream and ObjectInputStream.
Yes, ‘Serializable’ is a marker interface in Java language. It doesn’t declare any methods. It serves as a marker to indicate that the objects of the class implementing it can be serialized. Serialization is the process of converting an object into a stream.
There is an alternative available in Java language. We can use annotation instead of maker interface, which is metadata that can be attached to classes, methods, fields, or parameters.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved