Menu
Coddy logo textTech

Recap - Payment System

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 40 of 87.

challenge icon

Challenge

Easy

Let's build a complete payment processing system that brings together everything you've learned about interfaces in this chapter. You'll create a flexible system where different payment methods can be processed uniformly through a common interface.

You'll organize your code across five files:

  • Payable.java: Define the core interface that all payment methods must implement. It should declare a single method pay(double amount) that returns a String describing the payment action.
  • CreditCard.java: Create a class implementing Payable that represents credit card payments. A CreditCard has a cardNumber field (String) storing the last 4 digits. Include a constructor to initialize it. The pay method should return: Paid [amount] using Credit Card ending in [cardNumber]
  • PayPal.java: Create another class implementing Payable for PayPal payments. A PayPal account has an email field (String). Include a constructor to initialize it. The pay method should return: Paid [amount] via PayPal account [email]
  • PaymentProcessor.java: Create a processor class that can handle any Payable object. It should have a method processPayment(Payable paymentMethod, double amount) that calls the payment method's pay method and returns the result. This demonstrates how interfaces enable polymorphic behavior—the processor doesn't need to know the specific payment type!
  • Main.java: Bring everything together. You'll receive three inputs: a card number (last 4 digits), an email address, and a payment amount. Create a PaymentProcessor, then use it to process payments with both a CreditCard and a PayPal account for the given amount. Print each result on a separate line.

You will receive three inputs: the card number's last 4 digits (String), the PayPal email (String), and the payment amount (double).

Format amounts with two decimal places in your output. Notice how the same PaymentProcessor handles completely different payment types through the power of interfaces!

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs
        String cardNumber = scanner.nextLine();  // Last 4 digits
        String email = scanner.nextLine();       // PayPal email
        double amount = scanner.nextDouble();    // Payment amount
        
        // TODO: Create a PaymentProcessor
        
        // TODO: Create a CreditCard with the cardNumber
        
        // TODO: Create a PayPal account with the email
        
        // TODO: Process payment with CreditCard and print the result
        
        // TODO: Process payment with PayPal and print the result
    }
}

All lessons in Object Oriented Programming