写一个名为Account的类模拟账户。该类的属性和方法如下图所示。该类包括的属性:账号id,余额balance,年利率annualInterestRate;包含的方法:访问器方法(getter和setter方法),返回月利率的方法getMonthlyInterest(),取款方法withdraw(),存款方法deposit Java代码
时间: 2024-04-21 13:24:25 浏览: 167
Python 类的说明
4星 · 用户满意度95%
以下是使用Java语言实现的`Account`类的代码示例:
```java
class Account {
private int accountId;
private double balance;
private double annualInterestRate;
public Account(int accountId, double balance, double annualInterestRate) {
this.accountId = accountId;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterest() {
return balance * (annualInterestRate / 12);
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("成功取出:" + amount + "元");
} else {
System.out.println("余额不足,取款失败");
}
}
public void deposit(double amount) {
balance += amount;
System.out.println("成功存入:" + amount + "元");
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account(123456, 1000.0, 0.05);
System.out.println("账户ID:" + account.getAccountId());
System.out.println("当前余额:" + account.getBalance());
System.out.println("月利率:" + account.getMonthlyInterest());
account.withdraw(500);
System.out.println("当前余额:" + account.getBalance());
account.deposit(200);
System.out.println("当前余额:" + account.getBalance());
}
}
```
以上代码定义了一个`Account`类,包括账号ID、余额和年利率等属性。该类提供了相应的访问器方法(getter和setter方法)以及返回月利率、取款和存款等方法。
在`Main`类的`main`方法中,创建了一个`Account`对象,并通过访问器方法获取和设置属性值。然后调用取款和存款方法来模拟账户的操作,并输出相应的结果。
阅读全文