LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 1

Payment gateways behind one interface in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Define a PaymentGateway interface with pay(amount) and name(), plus a default receipt(amount); implement Razorpay-style, Paytm-style and Bank gateways and process an order through each.

Solution
Main.java
interface PaymentGateway {
    String name();
    boolean pay(double amount);
    default String receipt(double amount) {
        return pay(amount) ? String.format("%-8s paid Rs %.2f", name(), amount) : name() + " declined Rs " + amount;
    }
}

class CardGateway implements PaymentGateway {
    public String name() { return "Card"; }
    public boolean pay(double a) { return a <= 50000; }
}

class WalletGateway implements PaymentGateway {
    private double balance = 2000;
    public String name() { return "Wallet"; }
    public boolean pay(double a) { if (a > balance) return false; balance -= a; return true; }
}

class BankGateway implements PaymentGateway {
    public String name() { return "NetBank"; }
    public boolean pay(double a) { return a >= 100; }
}

public class Main {
    public static void main(String[] args) {
        PaymentGateway[] gateways = {new CardGateway(), new WalletGateway(), new BankGateway()};
        for (double amt : new double[]{1500, 60000}) {
            for (PaymentGateway g : gateways) System.out.println(g.receipt(amt));
        }
    }
}

Output Verified by compiling and running

Card     paid Rs 1500.00
Wallet   paid Rs 1500.00
NetBank  paid Rs 1500.00
Card declined Rs 60000.0
Wallet declined Rs 60000.0
NetBank  paid Rs 60000.00

The default receipt() works for every gateway; each class only answers name() and pay().

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