LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Records, Enums and Sealed Programs · Question 3

Payment results as a sealed hierarchy in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Model a payment outcome as a sealed interface with Success, Declined and Failed records; simulate several payments and produce user messages and a summary with an exhaustive switch.

Solution
Main.java
import java.util.List;

sealed interface PaymentResult permits Success, Declined, Failed { }
record Success(String txnId, int amount) implements PaymentResult { }
record Declined(String reason) implements PaymentResult { }
record Failed(String error, boolean retryable) implements PaymentResult { }

public class Main {
    static PaymentResult pay(String card, int amount) {
        if (card.startsWith("0")) return new Declined("card blocked");
        if (amount > 50000) return new Declined("limit exceeded");
        if (card.endsWith("9")) return new Failed("gateway timeout", true);
        return new Success("TXN" + (card.hashCode() & 0xFFF), amount);
    }

    static String message(PaymentResult r) {
        return switch (r) {
            case Success(var id, var amt) -> "paid Rs " + amt + " (" + id + ")";
            case Declined(var why) -> "declined: " + why;
            case Failed(var err, var retry) when retry -> "temporary problem (" + err + "), please retry";
            case Failed(var err, var retry) -> "failed: " + err;
        };
    }

    public static void main(String[] args) {
        List<PaymentResult> results = List.of(pay("4111", 1200), pay("0111", 500), pay("4119", 800), pay("4222", 75000));
        results.forEach(r -> System.out.println(message(r)));
        long ok = results.stream().filter(r -> r instanceof Success).count();
        int collected = results.stream().mapToInt(r -> r instanceof Success s ? s.amount() : 0).sum();
        System.out.println(ok + " of " + results.size() + " succeeded, collected Rs " + collected);
    }
}

Output Verified by compiling and running

paid Rs 1200 (TXN349)
declined: card blocked
temporary problem (gateway timeout), please retry
declined: limit exceeded
1 of 4 succeeded, collected Rs 1200

Each outcome carries exactly the data it needs; the compiler guarantees every switch handles all three.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links