Junior — Middle
Can you give an example of a situation where the system depends on abstraction rather than specific object implementations?
sobes.tech AI
Answer from AI
In Java, the principle of depending on abstractions rather than concrete implementations is often used to increase the flexibility and extensibility of the code. For example, if you have an interface PaymentProcessor with a method processPayment(), then the system can work with any implementations of this interface — CreditCardProcessor, PayPalProcessor, etc. The code that uses PaymentProcessor does not depend on a specific class, but only on the abstraction:
public interface PaymentProcessor {
void processPayment(double amount);
}
public class CreditCardProcessor implements PaymentProcessor {
public void processPayment(double amount) {
// implementation of credit card payment
}
}
public class OrderService {
private PaymentProcessor paymentProcessor;
public OrderService(PaymentProcessor paymentProcessor) {
this.paymentProcessor = paymentProcessor;
}
public void checkout(double amount) {
paymentProcessor.processPayment(amount);
}
}
Thus, OrderService depends on the abstraction PaymentProcessor, not on a specific implementation, which allows easily changing the payment method without modifying the service code.