Marker interfaces are interfaces that do not contain any methods or fields. They are also known as tagging interfaces. The purpose of a marker interface is to provide runtime type information about objects. This allows the compiler and JVM to have more information about the object.
Here is an example of a marker interface:
public interface Serializable {
}
Some examples of marker interfaces in Java include:
- Serializable: This interface indicates that an object can be serialized.
- Cloneable: This interface indicates that an object can be cloned.
- Remote: This interface indicates that an object is remote.
Here is an example of a class that implements the Serializable interface:
public class MyClass implements Serializable {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Because it implements the Serializable interface, this class is capable of being serialized. This implies that it can be sent across a network or stored on a file after being converted to a byte stream.
Java code can be made more functional and aesthetically pleasing by utilizing marker interfaces, which are an effective tool. They should only be utilized in moderation though, as they can make code harder to read.