LearnFrenzy
Sign in Take a free test

Polymorphism and Method Overriding · Polymorphism Programs · Question 1

Payment gateway with overridden fee rules in Java Solution, output & explanation

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

Write a Payment superclass and UPI, Credit Card (2% fee, minimum ₹10) and Wallet (1% cashback) subclasses; process a list of payments through one method and print a summary.

Solution
Main.java
import java.util.List;

abstract class Payment {
    protected final double amount;
    Payment(double amount) { this.amount = amount; }
    abstract String mode();
    double fee() { return 0; }
    double cashback() { return 0; }
    final double netCharged() { return amount + fee() - cashback(); }
}

class Upi extends Payment {
    Upi(double a) { super(a); }
    String mode() { return "UPI"; }
}

class CreditCard extends Payment {
    CreditCard(double a) { super(a); }
    String mode() { return "Card"; }
    @Override double fee() { return Math.max(10, amount * 0.02); }
}

class Wallet extends Payment {
    Wallet(double a) { super(a); }
    String mode() { return "Wallet"; }
    @Override double cashback() { return amount * 0.01; }
}

public class Main {
    public static void main(String[] args) {
        List<Payment> payments = List.of(new Upi(250), new CreditCard(300), new CreditCard(2400), new Wallet(800));
        double total = 0;
        for (Payment p : payments) {
            System.out.printf("%-6s %8.2f fee %6.2f cashback %5.2f net %8.2f%n", p.mode(), p.amount, p.fee(), p.cashback(), p.netCharged());
            total += p.netCharged();
        }
        System.out.printf("collected %.2f%n", total);
    }
}

Output Verified by compiling and running

UPI      250.00 fee   0.00 cashback  0.00 net   250.00
Card     300.00 fee  10.00 cashback  0.00 net   310.00
Card    2400.00 fee  48.00 cashback  0.00 net  2448.00
Wallet   800.00 fee   0.00 cashback  8.00 net   792.00
collected 3800.00

netCharged() is written once and final; the fee() and cashback() it calls are dispatched to each subclass.

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