Junior — Middle
In what situations is it recommended to use interfaces in development?
sobes.tech AI
Answer from AI
Interfaces in Java are recommended to be used in the following situations:
- To define a contract that different classes must implement, ensuring polymorphism.
- When you need to separate the declaration of behavior from its implementation, so that implementations can be changed without modifying the code that uses the interface.
- To simplify testing by allowing real implementations to be replaced with mocks or stubs.
- When designing architecture using SOLID principles, especially the Interface Segregation Principle (ISP) and Dependency Inversion Principle (DIP).
- To implement event-driven models, callbacks, and other patterns where abstraction is important.
Example:
public interface PaymentProcessor {
void processPayment(double amount);
}
public class PaypalProcessor implements PaymentProcessor {
public void processPayment(double amount) {
// implementation via PayPal
}
}
public class OrderService {
private PaymentProcessor paymentProcessor;
public OrderService(PaymentProcessor paymentProcessor) {
this.paymentProcessor = paymentProcessor;
}
public void checkout(double amount) {
paymentProcessor.processPayment(amount);
}
}