Senior
What is a marker interface? Why is it needed?
sobes.tech AI
Answer from AI
Marker interface is an interface without methods that serves to mark or identify a class as possessing a certain property.
An example in Java is the Serializable interface. A class implementing this interface signals to the JVM and other tools that its objects can be serialized.
Why is a marker interface needed:
- It allows using
instanceofto check if an object belongs to a certain category. - It is used in APIs and frameworks to enable or disable certain behaviors without adding methods.
- It provides type safety and code clarity.
Example:
public interface MyMarker {}
public class MyClass implements MyMarker {
// the class does not need to implement anything
}
// somewhere in the code
if (obj instanceof MyMarker) {
// perform special logic
}
Thus, a marker interface is a simple way to mark a class for subsequent processing.