java2.定义一个银行账户类Account,该类的成员变量有“账号“、“存款余额”,定义操纵类成员变量的set和get方法,定义一个Bank类,该类的成员变量account是Account类型,完成
时间: 2024-09-23 15:02:01 浏览: 86
在Java中,你可以创建一个`Account`类来代表银行账户的基本结构,例如存储账号和存款余额。首先,我们定义`Account`类:
```java
public class Account {
private String accountNumber; // 账号
private double balance; // 存款余额
// 构造函数
public Account(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// 设置账户信息的方法
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setBalance(double balance) {
if (balance >= 0) { // 避免负数余额
this.balance = balance;
} else {
System.out.println("Invalid balance! Please enter a non-negative amount.");
}
}
// 获取账户信息的方法
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
// 其他相关操作,如转账等...
}
```
接下来,我们可以定义`Bank`类,它有一个`Account`类型的成员变量`account`:
```java
public class Bank {
private Account account;
// 构造函数,初始化账户
public Bank(Account account) {
this.account = account;
}
// 如果需要的话,可以添加方法来管理银行账户,比如存款、取款等
public void deposit(double amount) {
account.setBalance(account.getBalance() + amount);
}
public void withdraw(double amount) {
if (amount <= account.getBalance()) {
account.setBalance(account.getBalance() - amount);
} else {
System.out.println("Insufficient funds!");
}
}
// 获取账户信息
public Account getAccount() {
return account;
}
}
```
阅读全文