Built in marker interfaces in java
In Java, there are several built-in marker interfaces that are defined in the Java API and serve specific purposes. These interfaces don’t contain any methods or fields; they are used to indicate certain characteristics or behaviors of classes that implement them. Here are some of the common built-in marker interfaces in Java:
1. Serializable:
The java.io.Serializable
interface is used to mark classes that can be serialized. Serialization is the process of converting an object’s state into a byte stream, which can be persisted or transmitted and reconstructed later. Classes implementing Serializable
indicate that their instances can be serialized and deserialized.
/*
* Author: Zameer Ali
* */
public interface Serializable {
// No methods, just a marker interface
}
2. Cloneable:
The java.lang.Cloneable
interface is used to indicate that the instances of a class can be cloned. The clone()
method, inherited from Object
, is used to create a shallow copy of an object. Classes implementing Cloneable
indicate that their instances can be cloned.
/*
* Author: Zameer Ali
* */
public interface Cloneable {
// No methods, just a marker interface
}
3. Remote (for Remote Method Invocation – RMI):
The java.rmi.Remote
interface is used in Java Remote Method Invocation (RMI) to identify remote objects. Remote objects can be accessed from a different Java Virtual Machine (JVM) over the network.
/*
* Author: Zameer Ali
* */
public interface Remote {
// No methods, just a marker interface
}
4. EventObject (for Event Handling):
The java.util.EventObject
class is not a marker interface, but it’s related to event handling in Java. It is the root class for all event objects. Classes extending EventObject
are used in event-driven programming to represent events.
/*
* Author: Zameer Ali
* */
public class EventObject extends Object implements Serializable {
// Class definition for event objects
}
5. Annotation (for Annotations):
The java.lang.annotation.Annotation
interface is not a marker interface, but it’s fundamental for working with annotations in Java. All annotation types automatically implement this interface.
/*
* Author: Zameer Ali
* */
public interface Annotation {
// Methods for annotation elements (not part of the marker interface pattern)
}
Remember that while these are some of the built-in marker interfaces in Java, modern Java programming often utilizes annotations and other mechanisms to achieve similar goals more flexibly. Annotations provide a powerful way to attach metadata to code elements, and they can carry additional information beyond what simple marker interfaces can convey.