AlgoMaster Logo

Interfaces

Ashish

Ashish Pratap Singh

In object-oriented design, interfaces play a foundational role in building systems that are extensible, testable, and loosely coupled.

hey allow different parts of the system to interact through well-defined contracts without needing to know how the behavior is actually implemented.

1. What is an Interface?

At its core, an interface defines a contract: a set of method signatures that any implementing class must fulfill. It declares what a class can do, but not how it does it.

2. Key Properties of Interfaces

Defines behavior without dictating implementation

An interface specifies what operations are expected, but not how they are carried out. This gives freedom to implementers to provide customized logic while still honoring the contract.

Enables polymorphism

Different classes can implement the same interface in different ways. This allows your code to work with different implementations interchangeably.

Promotes decoupling

Code that depends on interfaces is insulated from changes in concrete implementations. This reduces the ripple effect of changes and increases testability and maintainability.

3. Example: Payment Gateway Interface

Let’s say you’re designing a payment processing module that supports multiple providers like Stripe, Razorpay, and PayPal.

You can define a generic interface:

This interface doesn’t care how the payment is processed—it only mandates that all implementing classes must define a method called initiatePayment().

Now you can create multiple implementations:

Both StripePayment and RazorpayPayment implement the same interface, but the actual logic for processing the payment is different.

Usage: Loose Coupling in Action

Now let’s say you have a CheckoutService that processes payments. Instead of hardcoding a specific payment gateway, you inject the interface:

Now you can plug in any payment gateway at runtime:

No change required in CheckoutService