Sobes.tech
Junior

Why are methods not defined in some interfaces?

sobes.tech AI

Answer from AI

Marker interfaces do not define methods. They serve to mark a class, indicating that it has a certain characteristic or capability.

Examples of marker interfaces:

  • java.io.Serializable: Marks a class whose objects can be serialized.
  • java.lang.Cloneable: Marks a class whose objects can be cloned (support the clone() method).
  • java.util.RandomAccess: Marks lists that support fast (constant time) random access to their elements.

Using marker interfaces allows:

  • Identifying classes: Checking the type of an object for membership in a certain group using the instanceof operator.
    // check if an object is serializable
    if (object instanceof Serializable) {
        // perform serialization
    }
    
  • Changing behavior: APIs can change their behavior depending on whether a class implements a marker interface. For example, if a list implements RandomAccess, operations on it can be optimized.
  • Restricting access: Some APIs may require objects passed to them to implement a certain marker interface.
  • Annotations: In more modern approaches, many use annotations to achieve similar effects as marker interfaces. However, marker interfaces are still used in the Java standard library and legacy code.