java定义一个类实现银行帐户的概念,包括的成员变量有"帐号"和"存款余额",包括的方法有"存款"、"取款"、"查询余额"和”显示帐号”。定义主类,创建帐户类的对象,并完成相应操作。
时间: 2023-09-24 12:09:44 浏览: 457
定义一个类实现银行帐户的概念,包括的变量有
BankAccount类的定义如下:
```
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("余额不足!");
}
}
public double getBalance() {
return balance;
}
public void displayAccountNumber() {
System.out.println("账号:" + accountNumber);
}
}
```
主类的代码如下:
```
public class Main {
public static void main(String[] args) {
// 创建一个帐户
BankAccount account = new BankAccount("1234567890", 1000.0);
// 存款
account.deposit(500.0);
// 取款
account.withdraw(200.0);
// 查询余额
double balance = account.getBalance();
System.out.println("余额:" + balance);
// 显示帐号
account.displayAccountNumber();
}
}
```
输出结果为:
```
余额:1300.0
账号:1234567890
```
阅读全文