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
相关推荐
大侠归来几秒前
Spring Boot 2.1 → 3.5 迁移推演:从实战出发的完整路线图
java·spring boot·后端
源图客12 分钟前
浏览器开发者工具使用
开发语言·php
海马22 分钟前
Spring Boot 开发知识整理
java·spring boot·后端
谢亮_vipxieliang29 分钟前
Spring Boot 3.x 从零开始——环境搭建与第一个 REST 项目
java·spring boot·后端
念何架构之路32 分钟前
go-grpc核心抽象接口
开发语言·后端·golang
kimnoic33 分钟前
Python操作Git命令的详细指南
开发语言·python
FYKJ_20101 小时前
django个性化新闻推荐35173-计算机课程设计、毕业设计
java·spring boot·后端·python·架构·django·课程设计
kimnoic1 小时前
Python数据库sqlite3图文实例详解
开发语言·python
夜之眷属1 小时前
服务启动即崩:InetAddress.getLocalHost() 抛 UnknownHostException 排查记
java·运维·后端·docker
老王爱玩车1 小时前
文件操作从打开到缓冲区
c语言·开发语言·学习