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
相关推荐
不要秃头啊28 分钟前
别再谈提效了:AI 时代的开发范式本质变了
前端·后端·程序员
有志1 小时前
Java 项目添加慢 SQL 查询工具实践
后端
山佳的山1 小时前
KingbaseES 共享锁(SHARE)与排他锁(EXCLUSIVE)详解及测试复现
后端
Leo8991 小时前
rust 从零单排 之 一战到底
后端
程序员清风2 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
鱼人3 小时前
MySQL 实战入门:从“增删改查”到“高效查询”的核心指南
后端
大鹏19883 小时前
告别 Session:Spring Boot 实现 JWT 无状态登录认证全攻略
后端
Java编程爱好者3 小时前
从 AQS 到 ReentrantLock:搞懂同步队列与条件队列,这一篇就够了
后端
鱼人3 小时前
Nginx 全能指南:从反向代理到负载均衡,一篇打通任督二脉
后端
UIUV3 小时前
node:child_process spawn 模块学习笔记
javascript·后端·node.js