scala 学习笔记十二 继承

  1、介绍

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

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

    单一继承

    

    多层继承

    

    多重继承

    

    

扫描二维码关注公众号,回复: 2461669 查看本文章

  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)
  }

    

猜你喜欢

转载自www.cnblogs.com/shaosks/p/9390761.html