Course contentsShow
← Java
Lesson 496 of 2,87012. Abstract Classes and InterfacesFree lesson

Real-World Example: Implementing a Custom Interface

Building a complete example where multiple classes implement a common interface to demonstrate contract fulfillment.

Real-World Example: Implementing a Custom Interface

What you'll learn: You'll see how multiple unrelated classes can implement the same interface to fulfill a common contract in a practical scenario.

The Scenario

Imagine you're building a payment processing system. Different payment methods (credit card, PayPal, cryptocurrency) are completely different internally, but they all need to perform the same basic operation: process a payment.

Defining the Contract

public interface Payable {
    boolean processPayment(double amount);
    String getPaymentDetails();
}

This interface establishes a contract: any class implementing Payable must provide these two methods.

Multiple Implementations

public class CreditCardPayment implements Payable {
    private String cardNumber;
    
    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }
    
    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing $" + amount + " via credit card");
        return true;
    }
    
    @Override
    public String getPaymentDetails() {
        return "Credit Card ending in " + cardNumber.substring(cardNumber.length() - 4);
    }
}

public class PayPalPayment implements Payable {
    private String email;
    
    public PayPalPayment(String email) {
        this.email = email;
    }
    
    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing $" + amount + " via PayPal");
        return true;
    }
    
    @Override
    public String getPaymentDetails() {
        return "PayPal account: " + email;
    }
}

Using Polymorphism

Payable payment1 = new CreditCardPayment("1234567812345678");
Payable payment2 = new PayPalPayment("user@example.com");

payment1.processPayment(99.99);
payment2.processPayment(49.99);

Both objects are treated uniformly through the Payable interface, even though their internal implementations differ completely. The interface guarantees that any Payable reference can call these methods.

Key Takeaway: Interfaces allow completely different classes to fulfill a common contract, enabling polymorphic code that works with any implementation uniformly.