//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)
//存入200
xiaohua.deposit(200)
//取出150
xiaohua.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 += money
to.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)
//存入200
xiaohua.deposit(200)
//取出150
xiaohua.withdraw(150)
//转账给小明
xiaohua.transfer(xiaoming,100)
xiaohua.showMoney()
xiaoming.showMoney()
// println(xiaohua.balance)
}
}
输出结果
现在的余额是:200
现在的余额是:0