scala学习笔记(七) 继承

Scala在继承上面与java的一些差别:

1scala重写一个非抽象方法必须加 override关键字

2、只有主构造器可以调用父类的主构造器

 

类型检查与使用上,不再是使用java instanceOf来判断了,而是使用

isInstanceOf来进行判断对象,使用asInstanceOf来转换对象,例如:

If(p.isInstanceOf[A]){

val s = p.asInstanceOf[A]

}

这里说明一下,如果pnull上面的判断并不会抛出异常,而是返回false

并且上面的例子中如果pA的子类对象,也会成功,如果要具体判断p是否是A的对象,而又不包括其子类,可以这样

If(p.getClass== classOf[A])

 

另外一种更加scala的做法是使用模式匹配

P match {

    case s: A => …

    case _ =>

}

package demo

/**
 * @author Administrator
 *
 * scala 继承学习
 */
object ScalaExtends {

  def main(args: Array[String]): Unit = {
    val ca = new CheckingAccount(100)
    println(ca.deposit(100))
    println(ca.withdraw(80))
  }

}

class BankAccount(initialBalance: Double) {
  private var balance = initialBalance

  def currentBalance = balance

  def deposit(amount: Double) = {
    balance += amount
    balance
  }

  def withdraw(amount: Double) = {
    balance -= amount
    balance
  }
}

class CheckingAccount(initialBalance: Double) extends BankAccount(initialBalance: Double) {

  override def deposit(amount: Double) = {
    super.deposit(amount)
    factorage(1)
  }

  override def withdraw(amount: Double) = {
    super.withdraw(amount)
    factorage(1)
  }

  def factorage(amount: Double) = {
    super.withdraw(1)
  }

}

class SavingsAccount(initialBalance: Double) extends BankAccount(initialBalance: Double) {

  private var freeCount: Int = 3

  val currentBlance = super.currentBalance

  override def deposit(amount: Double) = {
    factorage(1)
    super.deposit(amount)
  }

  override def withdraw(amount: Double) = {
    factorage(1)
    super.withdraw(amount)
  }

  def factorage(amount: Double) {
    if (freeCount <= 0) {
      super.withdraw(1)
    } else {
      freeCount = freeCount - 1
    }
  }

  def earnMonthlyInterest = {
    //按月利0.3%结息
    val v = currentBlance * 0.003
    super.deposit(v)
    freeCount = 3
  }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ALAN-YOUNG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值