Junior
Why are methods not defined in some interfaces?
sobes.tech AI
Answer from AI
These interfaces are called marker interfaces. They do not contain methods but serve to annotate classes, indicating certain properties or semantics of the class to the compiler or JVM.
Examples:
java.io.Serializable: Marks a class as serializable.java.lang.Cloneable: Indicates that an object can be cloned.java.util.RandomAccess: Optimizes random access to list elements.
Advantages:
- Semantics: Clearly indicate the developer's intent regarding the class.
- Polymorphism: Allow for polymorphic calls when working with a group of classes implementing a single marker interface.
- Annotation: Can be used to provide additional information to tools (e.g., frameworks, ORM).
Alternatives (depending on the context):
- Annotations (
@interface). - Abstract classes.
Marker interfaces are preferred when you need to denote an attribute of a class without adding behavior.