Careeroza
Real World Example
A Paytm-style Wallet
Payment apps must never allow a negative balance or a transfer of zero rupees. All rules live inside the class, and the transaction history is exposed read-only.
Example
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
PaymentWallet asha = new PaymentWallet("Asha", 1000);
PaymentWallet ravi = new PaymentWallet("Ravi", 200);
asha.transferTo(ravi, 300);
ravi.transferTo(asha, 900);
System.out.println(asha.getOwner() + ": " + asha.getBalance());
System.out.println(ravi.getOwner() + ": " + ravi.getBalance());
System.out.println("Asha history: " + asha.getHistory());
}
}
class PaymentWallet {
private final String owner;
private long balance;
private final List<String> history = new ArrayList<>();
PaymentWallet(String owner, long openingBalance) {
this.owner = owner;
this.balance = openingBalance;
}
public void transferTo(PaymentWallet to, long amount) {
if (amount <= 0 || amount > balance) {
System.out.println("Transfer of " + amount + " from " + owner + " declined");
return;
}
balance -= amount;
to.balance += amount; // same class, so private access is allowed
history.add("-" + amount + " to " + to.owner);
to.history.add("+" + amount + " from " + owner);
}
public String getOwner() { return owner; }
public long getBalance() { return balance; }
public List<String> getHistory() { return List.copyOf(history); }
}Output
Transfer of 900 from Ravi declined Asha: 700 Ravi: 500 Asha history: [-300 to Ravi]
Note: Real wallets store money as long paise or BigDecimal, never double, to avoid rounding errors.