封装:1、类的封装是指将对象的状态信息隐藏在对象内部,不允许外部程序直接访问对象的内部信息,而是通过该类提供的方法实现对内部信息的访问;
2、在定义一个类时,将类的属性私有化,即使用private关键字进行修饰类的属性。
1、编写程序,模拟银行账户存取款与转账来实现类的封装。
2、``本篇建立一个银行账户类(acount),每个账户包括账号、姓名、账户余额等三个属性,银行账户类具有建立新帐号、查询余额、存款、取款、转账(即从本账户把钱转给另一个账户)等功能。
public class account {
private int id;//账号
private String name;//姓名
private double balance;//余额
public account(int id, String name, double balance) {
this.id = id;
this.name = name;
this.balance = balance;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}//get,set方法对私有属性提供公有方法,实现封装
//账户信息
public void information() {
System.out.println("账户: " + id);
System.out.println("姓名: " + name);
System.out.println("余额: " + balance);
}
//取款
public void withDraw(double money) {
if (money > this.balance)
System.out.println("你的余额不足");
else
this.balance = (this.balance - money);
System.out.println("账户: "+ this.name + " 你的余额为: " + this.balance);
}
//存款
public void deposit(double money) {
this.balance = (this.balance + money);
System.out.println("账户: "+ this.name + " 你的余额为: " + this.balance);
}
//转账
public void transfer(account other,double money){
if(this.balance<money) {
System.out.println("您的余额不足,不能转账");
}
this.balance = (this.balance - money);
other.balance = other.balance + money;
System.out.println("账户: "+ this.name +" 你的余额为: " + this.balance);
}
}
创建Bank类对上述方法进行测试
测试内容如下:
具体如下:
创建(“001”,“张三”,1000)、(“002”,“李四”,300)两个账号,给两个账号各存入500元,张三取出200元,张三转给李四300元,最后显示2人余额。
public class Bank {
public static void main(String[] args) {
account zhangsan = new account(001,"张三",1000);//张三开户
account lisi = new account(002,"李四",300);//李四开户
zhangsan.deposit(500);
lisi.deposit(500);
zhangsan.withDraw(200);
zhangsan.transfer(lisi,300);
zhangsan.information();
lisi.information();
}
}
运行结果如下:
账户: 张三 你的余额为: 1500.0
账户: 李四 你的余额为: 800.0
账户: 张三 你的余额为: 1300.0
账户: 张三 你的余额为: 1000.0
账户: 1
姓名: 张三
余额: 1000.0
账户: 2
姓名: 李四
余额: 1100.0