Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Marker Interface in Java

Last Updated on November 27, 2023 by Ankit Kochar

In Java, a marker interface serves the purpose of conveying supplementary information about classes during runtime. Examples of marker interfaces, such as Serializable, enable the JVM to execute specific actions or optimizations depending on the interface’s existence. This functionality is significant as it grants finer control over how classes are handled by the JVM, unlocking additional capabilities like serialization and remote method invocation.

What is Marker Interface

In Java, a marker interface is an interface devoid of any methods or fields. Its primary function is to serve as a means of marking or tagging a class with a particular characteristic or behavior. When a class implements a marker interface, it communicates to the compiler or the runtime environment that the class possesses the specified behavior associated with the marker interface. This approach offers flexibility in appending behavior to classes without the necessity of adding explicit functionality. Notable examples of marker interfaces in Java encompass Serializable, Cloneable, and Remote, among others.

Syntax of Marker Interface in Java

public class MyClass implements MarkerInterfaceName {
    // Class implementation
}

Examples of Marker Interface in Java

Serializable: This interface is used to mark a class as serializable, meaning that it can be written to a stream and then read back in to recreate the object.

Syntax of Serializable:

   public class MyClass implements Serializable {
    // class definition here
}

Example of Serializable:

import java.io.*;

public class MyClass implements Serializable {
    private int value;
    
    public MyClass(int value) {
        this.value = value;
    }
    
    public int getValue() {
        return value;
    }
}

// Usage:
MyClass obj1 = new MyClass(10);

// Serialize the object to a file
try (ObjectOutputStream objoutputStream = new ObjectOutputStream(new FileOutputStream("data.bin"))) {
    objoutputStream.writeObject(obj1);
}

// Deserialize the object from the file
try (ObjectInputStream objinputStream = new ObjectInputStream(new FileInputStream("data.bin"))) {
    MyClass obj2 = (MyClass) objinputStream.readObject();
    System.out.println(obj2.getValue());
 }

Output:

10

Explanation for Serializable:
The above example shows how to use serialization in Java. By implementing the Serializable interface, instances of a class can be serialized and deserialized. ObjectOutputStream writes the serialized object to a file, and ObjectInputStream reads it back into memory. However, not all objects can be serialized. Objects with non-serializable references or classes that don’t implement Serializable will throw a NotSerializableException. Also, when serializing sensitive data, care should be taken as the serialized objects can be intercepted and read by attackers.

Cloneable: The process of cloning creates a new instance of the original object, which can then be modified independently without affecting the original.

Syntax for Cloneable:

public interface Cloneable{
}

Example for Cloneable:

public class MyClass implements Cloneable {
    private int value;
    
    public MyClass(int value) {
        this.value = value;
    }
    
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    public int getValue() {
        return value;
    }
}

// Usage:
MyClass obj1 = new MyClass(10);
MyClass obj2 = (MyClass) obj1.clone();
System.out.println(obj1.getValue());
System.out.println(obj2.getValue());

Output:

10 10

Explanation of Cloneable:
The above example defines a class with a private field, a constructor, and a method that returns the value of the field. The class implements the Cloneable interface and overrides the clone() method. Two objects of the class are created, one is cloned from the other, and the values of their fields are printed. The output will be the same value twice, as both objects have the same initial value and the cloned object has the same value as the original.

Remote: This interface is used to mark a remote object as being remotely accessible.

Syntax for Remote:

public interface Remote {
}

Example for Remote:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface MyRemoteInterface extends Remote {
    public String sayHello() throws RemoteException;
}

public class MyRemoteObject implements MyRemoteInterface {
    public String sayHello() throws RemoteException {
        return "Hello from remote object!";
    }
}

// Usage:
MyRemoteInterface obj = new MyRemoteObject();
String result = obj.sayHello();
System.out.println(result);

Output:

"Hello from remote object!"

Explanation for Remote:
The above example demonstrates RMI in Java. MyRemoteInterface extends the Remote interface and defines a single method sayHello(). MyRemoteObject implements this interface and provides the implementation for the sayHello() method. To use the MyRemoteObject instance remotely, it must be registered with an RMI registry using the java.rmi.Naming class or a similar mechanism. A remote client can then obtain a reference to the remote object using java.rmi.Naming.lookup() and invoke its sayHello() method. However, RMI adds complexity to an application, and secure implementation is crucial to prevent unauthorized access or data breaches.

Introduction to Annotations

Annotations in Java are a form of metadata that can be added to Java code elements, such as classes, methods, and fields, to provide additional information about them. Annotations are defined using the @interface keyword and can include elements that specify values for the annotation. Annotations can be used to provide information to the compiler and runtime, such as which methods should be overridden or which classes should be serialized, as well as to define custom behavior and extend the capabilities of Java programs.

Syntax for Annotations in Java

public @interface MyAnnotation {
    String value();
}

Example for Annotations in Java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {
    String name();
    int age();
}

@MyAnnotation(name="John", age=30)
public class MyClass {
    @MyAnnotation(name="Mary", age=25)
    public void myMethod() {
        // method body
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        Class cls = obj.getClass();
        MyAnnotation classAnno = cls.getAnnotation(MyAnnotation.class);
        MyAnnotation methodAnno = obj.getClass().getMethod("myMethod").getAnnotation(MyAnnotation.class);
        System.out.println("Class annotation: name=" + classAnno.name() + ", age=" + classAnno.age());
        System.out.println("Method annotation: name=" + methodAnno.name() + ", age=" + methodAnno.age());
    }
}

Explanation of annotations in java
In this example, we define an annotation MyAnnotation with two elements, name and age, which represent the name and age of a person. We apply this annotation to the MyClass class and the myMethod method, specifying different values for the elements. In the Main class, we create an instance of MyClass and use reflection to obtain the MyAnnotation annotation from the class and the method. We then print the values of the name and age elements of both annotations.

Output:

Class annotation: name=John, age=30
Method annotation: name=Mary, age=25

Marker Interface Vs Annotations

Here, are the differences of marker interface and annotations:

             Marker Interface        Annotations
1.A type of interface that does not contain any methods but is used to mark a class as having a certain capability or behavior. 1. A form of metadata that can be added to Java code elements, such as classes, methods, and fields, to provide additional information about them.
2. Used to mark a class as having a certain behavior or capability. 2. Used to provide information to the compiler or runtime about the code element it annotates.
3. Examples include Serializable, Cloneable, and Remote. 3.Examples include @Override, @Deprecated, and @SuppressWarnings.
4. They cannot contain any methods or properties. 4. They can include elements that specify values for the annotation.
5.Provides no additional functionality beyond marking a class. 5. Can be used to provide custom behavior or extend the capabilities of a program.
6. Considered to be an older and less flexible mechanism for extending the capabilities of Java programs. 6. Considered to be a more modern and flexible mechanism for extending the capabilities of Java programs.

Conclusion
In summary, marker interfaces in Java are a mechanism for marking or flagging classes with specific characteristics or behaviors. These interfaces, devoid of methods or fields, serve as indicators to the compiler or runtime environment, signaling that a class implementing them possesses certain desired traits. Marker interfaces provide a flexible way to add behavior to classes without introducing explicit functionality. Examples of marker interfaces in Java include Serializable, Cloneable, and Remote, each influencing the behavior of classes in distinct ways.

Frequently Asked Questions(FAQs) related to Marker Interface in Java

Here are some of the FAQs related to Marker Interface in Java

Q1: What is the primary purpose of a marker interface in Java?
A marker interface in Java is primarily used to mark or flag classes with specific characteristics or behaviors without adding any methods or fields. It provides a way to convey information to the compiler or runtime about the intended behavior of a class.

Q2: How does a marker interface differ from a regular interface in Java?
Unlike regular interfaces, marker interfaces do not contain any methods or fields. Their purpose is to serve as markers, indicating certain characteristics or behaviors of the classes that implement them.

Q3: Can a class implement multiple marker interfaces in Java?
Yes, a class in Java can implement multiple marker interfaces. This allows the class to convey the presence of various characteristics or behaviors.

Q4: Are marker interfaces the only way to convey metadata in Java?
No, in addition to marker interfaces, Java also uses annotations as a means of conveying metadata. Annotations provide a more flexible and extensible way to associate metadata with code elements.

Q5: Can marker interfaces be used for custom behaviors in Java applications?
Yes, marker interfaces can be utilized to define and convey custom behaviors in Java applications. Developers can create their own marker interfaces to indicate specific traits or features in their classes.

Leave a Reply

Your email address will not be published. Required fields are marked *