Junior — Middle
Can you give examples of interface types used in Java to define contracts between components?
sobes.tech AI
Answer from AI
In Java, interfaces are used to define contracts between components, meaning they describe a set of methods that a class must implement. Examples of interface types:
-
Functional interfaces — contain a single abstract method, used for lambda expressions and functional programming. For example,
Runnable,Callable,Comparator. -
Marker interfaces — contain no methods, used to mark classes, e.g.,
Serializable,Cloneable. -
API interfaces — describe the behavior of components, e.g.,
List,Map,Setin collections.
Example of a functional interface:
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
}
// Usage
Calculator sum = (a, b) -> a + b;
int result = sum.calculate(5, 3); // 8
Interfaces enable the creation of flexible and extensible architectures, ensuring loose coupling between components.