持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第25天,点击查看活动详情
实验题目
创建一个简单的银行程序包
实验目的
Java 语言中面向对象的封装性及构造器的创建和使用。
实验说明
在这个练习里,创建一个简单版本的 Account 类。将这个源文件放入 banking 程 序包中。在创建单个帐户的默认程序包中,已编写了一个测试程序 TestBanking。 这个测试程序初始化帐户余额,并可执行几种简单的事物处理。最后,该测试程 序 显示该帐户的最终余额。
提示
-
创建 banking 包
-
在 banking 包下创建 Account 类。该类必须实现上述 UML 框图中的模型。
-
声明一个私有对象属性:balance,这个属性保留了银行帐户的当前(或 即时)余额。
-
声明一个带有一个参数( init_balance )的公有构造器 ,这个参数为 balance 属性赋值。
-
声明一个公有方法 geBalance,该方法用于获取经常余额。
-
声明一个公有方法 deposit,该方法向当前余额增加金额。
-
声明一个公有方法 withdraw 从当前余额中减去金额。
-
打开TestBanking.java文件,按提示完成编写,并编译 TestBanking.java 文件。
-
运行 TestBanking 类。可以看到下列输出结果:
Creating an account with a 500.00 balance. Withdraw 150.00 Deposit 22.50 Withdraw 47.62 The account has a balance of 324.88
代码
【Account.java】类
package banking;
public class Account {
private double balance; //银行帐户的当前(或即时)余额
//公有构造器 ,这个参数为 balance 属性赋值
public Account(double init_balance) {
this.balance = init_balance;
}
//用于获取经常余额
public double getBalance() {
return balance;
}
//向当前余额增加金额
public void deposit(double amt){
balance+=amt;
}
//从当前余额中减去金额
public void withdraw(double amt){
balance-=amt;
}
}
【TestBanking】类
/*
* This class creates the program to test the banking classes.
* It creates a new Bank, sets the Customer (with an initial balance),
* and performs a series of transactions with the Account object.
*/
package banking;
import banking.*;
public class TestBanking {
public static void main(String[] args) {
Account account;
// Create an account that can has a 500.00 balance.
System.out.println("Creating an account with a 500.00 balance.");
//code
account = new Account(500.00);
System.out.println("Withdraw 150.00");
//code
account.withdraw(150.00);
System.out.println("Deposit 22.50");
//code
account.deposit(22.50);
System.out.println("Withdraw 47.62");
//code
account.withdraw(47.62);
// Print out the final account balance
System.out.println("The account has a balance of " + account.getBalance());
}
}