Scala 的例题:银行账户钱存取功能

private 方法

Scala 复制代码
​
package Test22
// 银行账户
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 Test22_1 {
  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(xiaohua,100)

    xiaohua.showMoney()
    xiaoming.showMoney()
  }
}

​
复制代码
private[this]方法
Scala 复制代码
package Test22
// 银行账户
class BankAccount(private[this] 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){
      //把自己减少
      balance -= money
      //把对方增加
//      to.balance += money
      to.deposit(money)
    }
  }
//  def test(to:BankAccount):Unit={
//    to.balance=0
//  }
}

object Test22_1 {
  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(xiaohua,100)

    xiaohua.showMoney()
    xiaoming.showMoney()
//    println(xiaohua.balance)
  }
}

Scala 的控制方法作用域有5种:

(1)默认访问权限

(2)protected 访问权限

(3)private 访问权限

(4)private[this]访问权限

(5)private[package]访问权限

Scala 复制代码
package Test22{

  class C() {
    private[p2] def test(): Unit = {
      println("test")
    }
  }

  object Test22_3 {
    def main(args: Array[String]): Unit = {
      var c1=new C()
      c1.test()
    }
  }
}
相关推荐
渣渣盟6 天前
Flink流处理:实时计算URL访问量TopN(基于时间窗口)
大数据·flink·scala
渣渣盟12 天前
Flink事件时间与窗口操作实战指南
大数据·flink·scala
深兰科技16 天前
深兰科技与淡水河谷合作推进:矿区示范加速落地
java·人工智能·python·c#·scala·symfony·深兰科技
渣渣盟19 天前
Flink流处理:温度跳变检测与状态管理
大数据·flink·scala
小冯不疯25 天前
金蝶云星空与轻易云集成平台数据对接方案
全文检索·scala
howard20051 个月前
1.6.2 掌握Scala数据结构 - 列表
scala·不可变列表·可变列表
howard20051 个月前
1.6.1 掌握Scala数据结构 - 数组
scala·定长数组·变长数组
渣渣盟1 个月前
Flink Table API与SQL流数据处理实战
大数据·sql·flink·scala
howard20051 个月前
1.5 掌握Scala内建控制结构
scala·内建控制结构
howard20051 个月前
1.1.2 Windows上安装Scala
scala·windows版本