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
相关推荐
Java面试题总结几秒前
2026年Java面试题最新整理,附白话答案
java·开发语言·jvm·笔记·spring·intellij-idea
大鹏说大话6 分钟前
前端性能优化全链路指南:从资源加载到渲染的极致体验
开发语言
芒果披萨6 分钟前
日志管理 logging
java·开发语言·c++
unicrom_深圳市由你创科技11 分钟前
C# 如何实现对象序列化
开发语言·c#
夜珀16 分钟前
AtomGit算力连接与实战全攻略
开发语言·人工智能
xyq202422 分钟前
SQLite 命令详解
开发语言
xinhuanjieyi26 分钟前
php setplayersjson实现类型转换和文件锁定机制应对高并发
android·开发语言·php
前端 贾公子41 分钟前
uniapp中@input修改input内容不生效 | 过滤赋值无效 | 连续非法字符不更新的问题
开发语言·前端·javascript
五阿哥永琪42 分钟前
从零读懂 Java 函数式接口:Function、Consumer、Supplier、Predicate
java·开发语言
蓝悦1 小时前
用 .bat 一键启动 Jupyter:多环境切换
后端