快学Scala习题解答—第八章 继承

本文介绍了Scala中的继承概念,通过实例展示了如何扩展BankAccount类创建CheckingAccount和SavingsAccount类,这两个子类覆盖了父类的方法以实现不同的操作逻辑。此外,还展示了类的构造过程和抽象类的应用。
摘要由CSDN通过智能技术生成

8 继承 
8.1 扩展如下的BankAccount类,新类CheckingAccount对每次存款和取款都收取1美元的手续费class BankAccount(initialBalance:Double){ 
    private var balance = initialBalance 
    def deposit(amount:Double) = { balance += amount; balance} 
    def withdraw(amount:Double) = {balance -= amount; balance} 
}
 
继承语法的使用。代码如下 

Scala代码   收藏代码
  1. class CheckingAccount(initialBalance:Double) extends BankAccount(initialBalance){  
  2.   override def deposit(amount: Double): Double = super.deposit(amount - 1)  
  3.   
  4.   override def withdraw(amount: Double): Double = super.withdraw(amount + 1)  
  5. }  


8.2 扩展前一个练习的BankAccount类,新类SavingsAccount每个月都有利息产生(earnMonthlyInterest方法被调用),并且有每月三次免手续费的存款或取款。在earnMonthlyInterest方法中重置交易计数。  
Scala代码   收藏代码
  1. class SavingsAccount(initialBalance:Double) extends BankAccount(initialBalance){  
  2.   private var num:Int = _  
  3.   
  4.   def earnMonthlyInterest()={  
  5.     num = 3  
  6.     super.deposit(1)  
  7.   }  
  8.   
  9.   override def deposit(amount: Double): Double = {  
  10.     num -= 1  
  11.     if(num < 0) super.deposit(amount - 1) else super.deposit(amount)  
  12.   }  
  13.   
  14.   override def withdraw(amount: Double): Double = {  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值