银行账号的简化实现:

scala> class BankAccount{
| private var bal: Int = 0
| def balance: Int = bal
| def deposit(amount: Int) {
| require(amount > 0)
| bal += amount
| }
|
| def withdraw(amount: Int): Boolean =
| if (amount > bal) false
| else{
| bal -= amount
| true
| }
| }
defined class BankAccount

BankAccount类定义了私有变量bal,以及三个公开的方法:balance返回当前余额;deposit向bal添加指定amount的金额;withdraw尝试从bal减少指定amount的金额并须要确保操作之后的余额不能变为负数。withdraw的返回值为Boolean类型,说明请求的资金是否被成功提取。

scala> val account = new BankAccount
account: BankAccount = BankAccount@18532dc scala> account deposit 100 scala> account withdraw 80
res1: Boolean = true scala> account withdraw 80
res2: Boolean = false scala> account.balance
res3: Int = 20

只定义getter和setter方法而不带有关联字段,这种做法不但可行,有时甚至很有必要。

scala> class Thermometer {
| var celsius: Float = _
| def fahrenheit = celsius * 9 / 5 + 32
| def fahrenheit_= (f: Float) {
| celsius = (f - 32) * 5 / 9
| }
| override def toString = fahrenheit + "F/" + celsius + "C"
| }
defined class Thermometer

celsius变量初始化设置为缺省值‘—',这个符号指定了变量的”初始化值“。精确的说,字段的初始化器”=_”把零值赋给该字段。这里的“零”的取值取决于字段的类型。对于数值类型来说是0,布尔类型是false,应用类型则是null。

scala> val t = new Thermometer
t: Thermometer = 32.0F/0.0C scala> t.celsius = 100
t.celsius: Float = 100.0 scala> t
res0: Thermometer = 212.0F/100.0C scala> t.fahrenheit = -40
t.fahrenheit: Float = -40.0 scala> t
res1: Thermometer = -40.0F/-40.0C

最新文章

  1. jaxb
  2. vs2008主题
  3. Fraction to Recurring Decimal
  4. Rocky4.2下安装金仓v7数据库(KingbaseES)
  5. Android-ListView类
  6. jQuery Jcrop API参数说明(中文版)(转)(图片剪切)
  7. Unity3D学习笔记——递归+非递归遍历GameObject的子物体
  8. 【学习笔记】【C语言】sizeof
  9. Linux命令zip和unzip
  10. poj 1556 The door
  11. Js 旋转平滑特效
  12. MVC4.0系统开发新手历程(二)
  13. POJ 2082Lost Cows<>
  14. 19.Linux-USB总线驱动分析
  15. iOS 开发笔记 - 导航到地图
  16. Linux crontab使用方法
  17. Eclipse在当前行之上插入一行
  18. VM workstation 与 VM vSphere的区别 [转载]
  19. PWA 入门: 写个非常简单的 PWA 页面
  20. FP-growth算法发现频繁项集(一)——构建FP树

热门文章

  1. 常见的mysql数据库sql语句的编写和运行结果
  2. pyinstaller 打包错误集锦
  3. NCPC 2016 October 8,2016 Artwork
  4. Entity Framework Core(3)-配置DbContext
  5. 深入理解Python生成器(Generator)
  6. python2.7 关于打印中文的各种方法
  7. 深入理解ajax系列第八篇
  8. 机器学习之路: python 回归树 DecisionTreeRegressor 预测波士顿房价
  9. css平移动画的实现
  10. [Arc058E] Iroha and Haiku