Challenge: Payment Methods
Completed
Write an interface Payment with double fee(double amount). Implement it in three classes:
Card: fee is 2% of the amountUpi: fee is 0Wallet: fee is a flat 5
Read a method name (card, upi or wallet) and an amount. Print the fee and the total to pay, both with 2 decimals.
Input
One line: method name and amount.
Output
Fee: <fee> Total: <amount + fee>
Example
Input
card 1000
Output
Fee: 20.00 Total: 1020.00
Editor
Java
Hints
Interface methods must be public in the class.
Use a Payment variable to hold whichever object you create.
Solution explanation
The code that prints the fee only knows about Payment. Adding a new payment type needs no change there.
Show solution
import java.util.Scanner;
interface Payment {
double fee(double amount);
}
class Card implements Payment {
public double fee(double amount) { return amount * 0.02; }
}
class Upi implements Payment {
public double fee(double amount) { return 0; }
}
class Wallet implements Payment {
public double fee(double amount) { return 5; }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String kind = sc.next();
double amount = sc.nextDouble();
Payment p;
if (kind.equals("card")) p = new Card();
else if (kind.equals("upi")) p = new Upi();
else p = new Wallet();
double fee = p.fee(amount);
System.out.printf("Fee: %.2f%n", fee);
System.out.printf("Total: %.2f%n", amount + fee);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module