Why Interfaces, Interfaces are used in Java to achieve loose coupling. which is a design principle whose aim is to reduce the dependencies that exist between many parts of the system.
how interfaces enable loose coupling:
Example of Loose Coupling Using Interfaces
public class CreditCardPaymentService implements PaymentService { @Override public void processPayment(double amount) { // Process payment using credit card } } public class PayPalPaymentService implements PaymentService { @Override public void processPayment(double amount) { // payment processing via PayPal } } public class OrderService { private final PaymentService paymentService; public OrderService(PaymentService paymentService) { this.paymentService = paymentService; } public void placeOrder(double amount) { paymentService.processPayment(amount); } } // Usage PaymentService paymentService = new CreditCardPaymentService(); OrderService orderService = new OrderService(paymentService); orderService.placeOrder(100.0);
as shown by the example, OrderService depends on the interface PaymentService, not on its implementation. This allows you to switch between multiple different ways of implementing payments without having to change the OrderService code.
The above is the detailed content of Interfaces in Java for Loose Coupling. For more information, please follow other related articles on the PHP Chinese website!