scala 学习笔记十二 继承

  1、介绍

    继承是面向对象的概念,用于代码的可重用性。可以通过使用extends关键字来实现继承。 为了实现继承,一个类必须扩展到其他类,被扩展类称为超类或父类。扩展的类称为派生类或子类。

    Scala支持各种类型的继承,包括单一,多层次,多重和混合。可以在类中使用单一,多层次和层次结构。多重和混合只能通过使用特征来实现。在这里,通过使用图形表示所有类型的继承

 

    单一继承

    

    多层继承

    

    多重继承

    

    

 

  2、例子

  

 class GreatApe(){
    def call ="GreatApe! "
    var energy = 3
    def eat() = {energy += 10; energy}
    def climb(x:Int) = energy -= x
  }

  class Bonobo extends GreatApe {
    override def call = "Bonobo "
    energy = 5
    override def eat() = super.eat() * 2
    def run() = "Bonobo runs"
  }

  class Chimpanzee extends GreatApe{
    override def call = "Chimpanzee "
    override def eat() = super.eat() * 3
    def jump() = "Chimpanzee jumps"
  }

  def main(args: Array[String]): Unit = {
   val obj1 = new GreatApe
    println(obj1.call) //GreatApe!
    println(obj1.energy)//3
    println(obj1.eat)//13
    println("\n")

    val obj2 = new Bonobo
    println(obj2.call)//Bonobo
    println(obj2.energy)//5
    println(obj2.eat)//30
    println("\n")

    val obj3 = new Chimpanzee
    println(obj3.call)
    println(obj3.energy)
    println(obj3.eat)
  }

 

 

 

 

    

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值