//eg:银行账户存钱取钱
// 账户类:
// -balance() 余额
// -deposit() 存钱
// -withdraw() 取钱
// -transfer(to:账户,amount:Dobule)转账
package Test1104
//银行账户class BankAccount(private var balance:Int){def showMoney():Unit ={println(s"现在的余额是:${balance}")}def deposit(money:Int):Unit ={balance += money}def withdraw(money:Int):Unit ={if(money <= balance)balance -= money}//转账def transfer(to:BankAccount,money:Int):Unit = {//A --200-->B//A 减少 B 增加}
}object Test11041 {def main(args: Array[String]): Unit = {var xiaoming = new BankAccount(0)var xiaohua = new BankAccount(100)//存入200xiaohua.deposit(200)//取出150xiaohua.withdraw(1500)//转账给小明xiaohua.transfer(100)xiaohua.showMoney()xiaoming.showMoney()// println(xiaohua.balance)}
}
package Test1104
//银行账户//private[this]:这个属性,只能在当前对象上使用!
class BankAccount(private var balance:Int){def showMoney():Unit ={println(s"现在的余额是:${balance}")}def deposit(money:Int):Unit ={balance += money}def withdraw(money:Int):Unit ={if(money <= balance)balance -= money}// 如何实现//转账:把当前的账户的余额全部转出 money 给 to 这个账户def transfer(to:BankAccount,money:Int):Unit = {//A --200-->B//A 减少 B 增加if(money <= balance){//把自己减少to.balance -= money//把对方增加to.balance += moneyto.deposit(money)}}
// def test(to:BankAccount):Unit ={
// to.balance = 0
// }
}object Test11041 {def main(args: Array[String]): Unit = {var xiaoming = new BankAccount(0)var xiaohua = new BankAccount(100)//存入200xiaohua.deposit(200)//取出150xiaohua.withdraw(150)//转账给小明xiaohua.transfer(xiaoming,100)xiaohua.showMoney()xiaoming.showMoney()// println(xiaohua.balance)}
}
输出结果
现在的余额是:200
现在的余额是:0