Java创建银行账号类SavingAccount,用静态变量存储年利率,用私有实例变量存储存款额。提供计算年利息的方法和计算月利息(年利息/12)的方法。编写一个测试程序测试该类,建立SavingAccount的对象saver,存款额是30000,设置年利率是3%,计算并显示saver的存款额、年利息和月利息;
时间: 2024-02-03 18:12:31 浏览: 163
Java关于银行账户类
下面是Java代码实现:
```java
public class SavingAccount {
private double balance; // 存款额
private static double annualInterestRate; // 年利率
public SavingAccount(double balance) {
this.balance = balance;
}
// 设置年利率
public static void setAnnualInterestRate(double rate) {
annualInterestRate = rate;
}
// 计算月利息
public double getMonthlyInterest() {
return balance * annualInterestRate / 12;
}
// 计算年利息
public double getAnnualInterest() {
return balance * annualInterestRate;
}
// 存款
public void deposit(double amount) {
balance += amount;
}
// 取款
public void withdraw(double amount) {
balance -= amount;
}
// 获取存款余额
public double getBalance() {
return balance;
}
}
public class TestSavingAccount {
public static void main(String[] args) {
SavingAccount saver = new SavingAccount(30000);
SavingAccount.setAnnualInterestRate(0.03); // 设置年利率为3%
double balance = saver.getBalance();
double annualInterest = saver.getAnnualInterest();
double monthlyInterest = saver.getMonthlyInterest();
System.out.println("存款额:" + balance);
System.out.println("年利息:" + annualInterest);
System.out.println("月利息:" + monthlyInterest);
}
}
```
运行结果:
```
存款额:30000.0
年利息:900.0
月利息:75.0
```
阅读全文