Abstraction helps achieve loose coupling by allowing classes to depend on interfaces or abstract definitions rather than concrete implementations. This reduces direct dependencies between components, making the application more flexible, maintainable, and easier to extend.
Key Points: • Abstraction hides implementation details and exposes only the required behavior. • Classes interact through interfaces or abstract classes instead of specific implementations. • Changes in one implementation have minimal impact on other parts of the application. • Loose coupling improves maintainability, testability, and scalability. • Modern frameworks such as Spring heavily rely on abstraction and dependency injection.
Example: Consider a payment processing system. The application should work with different payment methods such as Credit Card, UPI, or PayPal. By using an interface, the application depends only on the abstraction and not on a specific payment implementation.
Code Example:
interface PaymentService {
void pay(double amount);
}
class CreditCardPayment implements PaymentService {
@Override
public void pay(double amount) {
System.out.println("Paid using Credit Card");
}
}
class UpiPayment implements PaymentService {
@Override
public void pay(double amount) {
System.out.println("Paid using UPI");
}
}
class PaymentProcessor {
private PaymentService paymentService;
public PaymentProcessor(PaymentService paymentService) {
this.paymentService = paymentService;
}
public void processPayment(double amount) {
paymentService.pay(amount);
}
}
public class Demo {
public static void main(String[] args) {
PaymentService service =
new UpiPayment();
PaymentProcessor processor =
new PaymentProcessor(service);
processor.processPayment(1000);
}
}Output:
Paid using UPI
In this example, PaymentProcessor depends on the PaymentService interface rather than a specific implementation. New payment methods can be added without modifying the PaymentProcessor class.
Benefits of Loose Coupling Through Abstraction:
• Easier maintenance • Better scalability • Improved testability • Flexible implementation changes • Reduced dependency between modules
Interview Tip: A concise interview answer is:
"Abstraction promotes loose coupling by allowing classes to depend on interfaces or abstract classes instead of concrete implementations. This enables implementation changes without affecting dependent code, resulting in flexible, maintainable, and scalable applications."