Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum

A finished payment system to read: a PaymentMethod interface with a default payWithFee, an abstract BasePayment that writes pay() once, Card, Upi and Wallet rules, a Status enum, and a checkout where the Wallet with 50 declines 80 and the Card pays.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Read a small system built from an interface, an abstract base class and an enum
  • Use a default interface method that every implementing class gets for free
  • Explain why two orders sharing one Wallet reference share one balance
  • Trace a checkout that tries payment methods in order and stops at the first PAID

Before you start

  • Java interfaces
  • Java abstract classes
  • Java enums with fields, methods and switch

This lab is a finished payment system to read and run. It puts several OOP ideas to work together: an interface sets the contract, an abstract class shares the common work, three classes each add one rule, and an enum names the result.

The interface PaymentMethod declares name(), pay() and a default payWithFee(). The abstract class BasePayment implements it, stores the name and writes pay() once, leaving approve() abstract. Card, Upi and Wallet extend BasePayment and each write approve(). pay() returns a Status enum: PENDING, PAID or DECLINED. interface PaymentMethod name(), pay(), default payWithFee() abstract BasePayment name, pay() written once, approve() abstract Cardtotal <= 500 Upialways true Walletwithin balance enum Status PENDING PAID DECLINED
Contract on top, shared work in the middle, one rule per payment method.

The contract and the shared work

package org.studyeasy.s03l18;

public interface PaymentMethod {
    String name();
    Status pay(double total);

    default Status payWithFee(double total) {
        return pay(total + 2);
    }
}

name and pay have no bodies, so every payment method must provide them. payWithFee is a default method: it has a body, adds 2 to the total and calls pay, and every implementing class gets it for free.

package org.studyeasy.s03l18;

public abstract class BasePayment implements PaymentMethod {
    private final String name;

    protected BasePayment(String name) {
        this.name = name;
    }

    public String name() {
        return name;
    }

    protected abstract boolean approve(double total);

    public Status pay(double total) {
        Status result = approve(total) ? Status.PAID : Status.DECLINED;
        System.out.println(name + " " + total + " -> " + result);
        return result;
    }
}

pay is written once: it asks approve, turns true into PAID and false into DECLINED, prints one line and returns the status. approve is abstract on purpose (like monthlyPay), because each payment method decides for itself.

package org.studyeasy.s03l18;

public class Card extends BasePayment {
    private static final double LIMIT = 500;

    public Card() {
        super("Card");
    }

    protected boolean approve(double total) {
        return total <= LIMIT;
    }
}

That rule is all Card writes. Upi's approve returns true for everything.

One call, three behaviours

PaymentMethod[] methods = {
    new Card(), new Upi(), new Wallet(100)
};
for (PaymentMethod m : methods) {
    m.pay(80);
}
Card 80.0 -> PAID
UPI 80.0 -> PAID
Wallet 80.0 -> PAID

The loop only knows PaymentMethod. Each object answers through its own approve, and 80 is within every limit.

The default method adds the fee

PaymentMethod m = new Upi();
m.pay(80);
m.payWithFee(80);
UPI 80.0 -> PAID
UPI 82.0 -> PAID

Upi never wrote payWithFee. It's the interface's default, which calls pay(82).

Status has exactly three values

package org.studyeasy.s03l18;

public enum Status {
    PENDING("waiting"), PAID("done"), DECLINED("refused");

    private final String note;

    Status(String note) {
        this.note = note;
    }

    public String note() {
        return note;
    }
}
Status s = Status.valueOf("PAID");
System.out.println(Status.values().length + " " + (s == Status.PAID));
System.out.println(s + ": " + s.note());
String next = switch (s) {
    case PENDING -> "wait";
    case PAID -> "ship it";
    case DECLINED -> "ask for another method";
};
System.out.println(next);
3 true
PAID: done
ship it

The same enum tools as in enums with fields: valueOf, values, a field per constant and a switch with one branch per constant.

A Wallet remembers its balance

package org.studyeasy.s03l18;

public class Wallet extends BasePayment {
    private double balance;

    public Wallet(double balance) {
        super("Wallet");
        this.balance = balance;
    }

    protected boolean approve(double total) {
        if (total > balance) {
            return false;
        }
        balance -= total;
        return true;
    }

    public double balance() {
        return balance;
    }
}

Card and Upi keep nothing between payments; a wallet does. Now two orders use the same wallet:

static class Order {
    private final PaymentMethod method;
    Order(PaymentMethod method) {
        this.method = method;
    }
    void checkout(double total) {
        method.pay(total);
    }
}

public static void main(String[] args) {
    Wallet wallet = new Wallet(100);
    new Order(wallet).checkout(30);
    new Order(wallet).checkout(30);
    System.out.println("Left: " + wallet.balance());
}
Wallet 30.0 -> PAID
Wallet 30.0 -> PAID
Left: 40.0

Each order keeps a reference to the wallet, not a copy. There's only one Wallet object, so 100 becomes 70, then 40.

The lab also has an inner-class example: a Cart with an inner Summary. The summary is created while the total is 50, the total then changes to 80, and summary.text() prints Total: $80.0. The inner object holds no copy; it reads its outer cart at that moment (see inner classes).

The checkout

package org.studyeasy.s03l18;

public class Lab4_Checkout {
    public static void main(String[] args) {
        PaymentMethod[] tries = {
            new Wallet(50), new Card(), new Upi()
        };
        Status result = Status.PENDING;
        for (PaymentMethod m : tries) {
            result = m.pay(80);
            if (result == Status.PAID) {
                System.out.println("Paid with " + m.name());
                break;
            }
        }
        System.out.println("Final: " + result);
    }
}
Wallet 80.0 -> DECLINED
Card 80.0 -> PAID
Paid with Card
Final: PAID

The array lists methods in order of preference. The wallet has only 50, so 80 is declined and the loop goes on. The card approves it and break stops the loop, so the Upi is never tried.

Recap

PieceJob
PaymentMethod interfacethe contract, plus a default payWithFee
BasePayment abstract classshared name and pay; approve left to each child
Card, Upi, Walletone approve rule each
Status enumnames the result: PENDING, PAID, DECLINED
Shared referencetwo orders, one wallet, one balance

Try it yourself: add a GiftCard that approves only totals under 100, put it first in the checkout array, and predict the output before you run it.

Keep going in Java · 40 of 79

Previous
Java Enums with Fields, Methods and switch
Next post
Java Records: A Whole Data Class in One Line
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • The contract and the shared work
  • One call, three behaviours
  • The default method adds the fee
  • Status has exactly three values
  • A Wallet remembers its balance
  • The checkout
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.