mirror of
https://github.com/Dichgrem/Java.git
synced 2026-02-05 02:51:57 -05:00
78 lines
2.2 KiB
Java
78 lines
2.2 KiB
Java
package com.study.demo13;
|
|
|
|
interface Payable {
|
|
boolean pay(double amount);
|
|
String getPayType();
|
|
}
|
|
|
|
abstract class Account implements Payable {
|
|
protected double balance;
|
|
|
|
public Account(double balance) {
|
|
this.balance = balance;
|
|
}
|
|
|
|
protected boolean canPay(double total) {
|
|
return balance >= total;
|
|
}
|
|
|
|
public double getBalance() {
|
|
return balance;
|
|
}
|
|
}
|
|
|
|
class BankAccount extends Account {
|
|
public BankAccount(double balance) {
|
|
super(balance);
|
|
}
|
|
|
|
@Override
|
|
public boolean pay(double amount) {
|
|
if (canPay(amount)) {
|
|
balance -= amount;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
@Override
|
|
public String getPayType() {
|
|
return "BANK";
|
|
}
|
|
}
|
|
|
|
class WalletAccount extends Account {
|
|
public WalletAccount(double balance) {
|
|
super(balance);
|
|
}
|
|
|
|
@Override
|
|
public boolean pay(double amount) {
|
|
double total = amount * 1.05;
|
|
if (canPay(total)) {
|
|
balance -= total;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
@Override
|
|
public String getPayType() {
|
|
return "WALLET";
|
|
}
|
|
}
|
|
|
|
public class PaymentService {
|
|
public static void main(String[] args) {
|
|
Payable bank = new BankAccount(1000.0);
|
|
Payable wallet = new WalletAccount(500.0);
|
|
Payable bank2 = new BankAccount(100.0);
|
|
Payable wallet2 = new WalletAccount(50.0);
|
|
|
|
System.out.println("支付方式: " + bank.getPayType() + ", 支付 200: " + (bank.pay(200) ? "成功" : "失败") + ", 余额: " + ((BankAccount) bank).getBalance());
|
|
System.out.println("支付方式: " + wallet.getPayType() + ", 支付 100: " + (wallet.pay(100) ? "成功" : "失败") + ", 余额: " + String.format("%.2f", ((WalletAccount) wallet).getBalance()));
|
|
System.out.println("支付方式: " + bank.getPayType() + ", 支付 200: " + (bank2.pay(200) ? "成功" : "失败") + ", 余额: " + ((BankAccount) bank2).getBalance());
|
|
System.out.println("支付方式: " + wallet.getPayType() + ", 支付 100: " + (wallet2.pay(100) ? "成功" : "失败") + ", 余额: " + String.format("%.2f", ((WalletAccount) wallet2).getBalance()));
|
|
}
|
|
}
|