Scala中类的继承与多态

28 阅读2分钟

继承

1.定义:在原有类的基础上定义一个新类,原有类称为父类,新类称为子类。

2.语法格式:class 子类名 extends 父类名 { 类体 }

3.好处:复用代码和实现多态。复用代码:子类可以继承父类的特性。“多态”,“:” 子类可以在自己内部实现父类没有的特性。(不劳而获)

4。特点:继承了父类所具备的“技能”

5.问题:如果子类觉得父类的方法并不是自己要的,如何定义自己的方法呢?

解决方法:a.在子类中重写(覆盖)父类的方法 :override:重写 b.super 在子类内部通过 super 来访问父类

代码展示:

class Animal() {
    
    def run():Unit = {
      
    }
    def eating():Unit = {
      println("Animal eating")
    }
  }

  // Dog继承了Animal
  class Dog extends Animal(){
    
    // 在子类中重写(覆盖)父类的方法
      
    override def eating(): Unit = {
      // 调用父类方法?
      // 在子类内部,通过 super 来访问父类
      
      super.run()
      printlnn("你是狗,你有你自己吃饭的方式!!!")
    }
  }

  def main(args: Array[String]): Unit = {
    val dog1 = new Dog()
    dog1.eating()  // 调用自己的eating的方法
  }
}

多态

面向对象的编程语言有三大特性: 封装、继承、多态

多态的定义:同一个操作,作用于不同的对象,有不同的执行结果

代码展示:

class Animal() {
  def eating():Unit = {
    println("Animal eating")
  }
}

class Dog extends Animal(){
  // 在子类中重写(覆盖)父类的方法
  override def eating(): Unit = {
    println("你是狗,你吃饭大口大口吃")
  }
}


class Cat() extends Animal(){
  // 在子类中重写(覆盖)父类的方法
  override def eating(): Unit = {
    println("你是猫,你吃饭小口小口吃")
  }
}
def test(animal: Animal):Unit = {
  animal.eating()
}

def main(args: Array[String]): Unit = {
  val cat = new Cat()
  val dog = new Dog()

  test(cat)
  test(dog)
}

结果:

Snipaste_2025-11-04_11-30-14.png

调用顺序

存在继承关系的时候,构造器的调用顺序是先调用父类

父类构造器 -> 子类构造器

代码展示:

class Animal() {
  println("父类构造器被调用......")
}

// Dog 继承了 Animal
class Dog extends Animal(){
  println("子类构造器被调用......")
}

// Puppy 继承了 Dog
println("子类:Puppy 构造器被调用")

def main(args: Array[String]): Unit = {
  new Dog() // new 会自动调用构造器去生成对象
}

结果:

Snipaste_2025-11-04_11-31-02.png