Scala的属性访问权限(一)默认访问权限

Scala 复制代码
//eg:银行账户存钱取钱
//  账户类:
//  -balance()  余额
//  -deposit()  存钱
//  -withdraw() 取钱
//  -transfer(to:账户,amount:Dobule)转账
Scala 复制代码
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)


  }
}
Scala 复制代码
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)


  }
}

输出结果

Scala 复制代码
现在的余额是:200
现在的余额是:0
相关推荐
IT_陈寒8 小时前
Java 性能优化:5个被低估的JVM参数让你的应用吞吐量提升50%
前端·人工智能·后端
南囝coding8 小时前
《独立开发者精选工具》第 018 期
前端·后端
绝无仅有8 小时前
数据库MySQL 面试之死锁与排查经验总结
后端·面试·github
用户384958730699 小时前
Spring Boot 集成 Redis 的完整流程
后端
昨日的风9 小时前
springboot 多数据源切换
后端
绝无仅有9 小时前
mysql性能优化实战与总结
后端·面试·github
用户83562907805110 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下10 小时前
最终的信号类
开发语言·c++·算法
德育处主任10 小时前
玩转 Strands:AI Agent 开发,原来可以这么简单!
后端·aigc
Undoom10 小时前
大模型选型“炼狱”与终结:一份来自普通开发者的AI Ping深度评测报告
后端