创建银行卡类,设计两个子类:储蓄卡(取钱)和信用卡(取钱和借钱)。JAVA
时间: 2024-12-12 13:18:01 浏览: 11
在Java中,我们可以创建一个名为BankAccount的抽象基类,然后派生出两个具体的子类:SavingsAccount和CreditCard。这里是一个简单的例子:
```java
// 定义一个抽象银行账户类
public abstract class BankAccount {
protected String accountNumber;
protected double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// 公共方法:获取余额和转账操作
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public abstract void withdraw(double amount);
}
// 存款账户(储蓄卡)子类
public class SavingsAccount extends BankAccount {
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("取款金额超过可用余额");
}
}
}
// 信用卡子类
public class CreditCard extends BankAccount {
private int creditLimit;
public CreditCard(String accountNumber, double initialBalance, int creditLimit) {
super(accountNumber, initialBalance);
this.creditLimit = creditLimit;
}
@Override
public void withdraw(double amount) {
if (amount <= balance && amount <= creditLimit) {
balance -= amount;
} else if (amount > creditLimit) {
System.out.println("取款金额超过了信用额度");
} else {
System.out.println("取款金额超过当前可用余额");
}
}
// 这里可以添加借款功能
public void borrow(double amount) {
if (balance + amount <= creditLimit) {
balance += amount;
} else {
System.out.println("借款超出了信用额度");
}
}
}
阅读全文