编程实现:模拟银行账户功能。java用类和对象的方法
时间: 2024-10-20 19:16:37 浏览: 35
Java银行类的实现和面向对象编程的分析
在Java中,我们可以创建一个名为`BankAccount`的类来模拟银行账户的功能。这个类会包含基本的属性,如账户名、账号、余额等,以及一些操作方法,如存款、取款、查询余额等。以下是简单的实现:
```java
public class BankAccount {
private String accountName;
private int accountNumber;
private double balance;
// 构造函数
public BankAccount(String accountName, int accountNumber) {
this.accountName = accountName;
this.accountNumber = accountNumber;
this.balance = 0; // 初始余额为0
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(accountName + " deposited: " + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
// 取款方法
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println(accountName + " withdrew: " + amount);
} else {
System.out.println("Insufficient balance or invalid withdrawal amount.");
}
}
// 查询余额方法
public double checkBalance() {
return balance;
}
// 获取账户信息的方法
@Override
public String toString() {
return "Account Name: " + accountName + ", Account Number: " + accountNumber + ", Balance: " + balance;
}
}
```
在这个例子中,`BankAccount`是一个类,它有三个私有成员变量,通过公共的getter和setter方法(在这里省略)来访问。你可以创建`BankAccount`的对象并进行相应的操作,比如:
```java
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("John Doe", 123456789);
myAccount.deposit(1000);
myAccount.withdraw(500);
System.out.println(myAccount);
}
```
阅读全文