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
相关推荐
星秀日5 分钟前
框架--SpringMVC
java·开发语言·servlet
小蒜学长10 分钟前
springboot餐厅信息管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端
Chh4322433 分钟前
React 新版
后端
Miracle6581 小时前
【征文计划】Rokid CXR-M SDK全解析:从设备连接到语音交互的AR协同开发指南
后端
勤奋菲菲1 小时前
Vue3+Three.js:requestAnimationFrame的详细介绍
开发语言·javascript·three.js·前端可视化
合作小小程序员小小店1 小时前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
要天天开心啊1 小时前
Java序列化和反序列化
java·开发语言
二宝1521 小时前
黑马商城day1-MyBatis-Plus
java·开发语言·mybatis
笃行3502 小时前
基于Rokid CXR-S SDK的智能AR翻译助手技术拆解与实现指南
后端
Porunarufu2 小时前
JAVA·类和对象③封装及包
java·开发语言