再水一期

19 阅读2分钟
package level02

import java.io.FileWriter

object class06 {
  /**
   * 继承
   * extends
   * 好处:不劳而获
   */
  class Animal() {
    def eating(): Unit = {
      println("Animal eating")
    }
  }

  // Dog 继承了 Animal
  class Dog extends Animal() {
  }

  def main(args: Array[String]): Unit = {
    val dog1 = new Dog()
    dog1.eating() // 直接可以使用父类的方法
  }
}

image.png

package level02

import java.io.FileWriter

object class07 {
  /**
   * 继承
   * extends
   * 好处:不劳而获
   *
   * 问题:
   * 如果子类觉得父类的方法并不是自己要的,如何定义自己的方法呢?
   * 1. override 重写
   * 2. super 在子类内部,通过super来访问父类
   */
  class Animal() {
    def eating(): Unit = {
      println("Animal eating")
    }
  }

  // Dog 继承了 Animal
  class Dog extends Animal() {
    // 在子类中重写(覆盖)父类的方法
    override def eating(): Unit = {
      // 调用父类的方法
      super.eating()
      println("我是狗,我有自己的吃饭的方式!")
    }
  }

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

image.png

package level02

import java.io.FileWriter

object class08 {
  /*
  *  面向对象的编程语言有三大特性:封装,继承,多态
  *
  *  多态: 同一个操作,作用于不同的对象,有不同的执行结果。
  *
   */
  class Animal() {
    def eating(): Unit = {
      println("Animal eating")
    }
  }

  // Dog 继承了 Animal
  class Dog extends Animal() {
    override def eating(): Unit = {
      println("我是狗,我吃饭大口大口嚼")
    }
  }

  // Cat 继承了 Animal
  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)
  }
}

image.png

package level02

object class09 {
  /**
   * 存在继承关系的时候,构造器的调用顺序?
   * 父类构造器 -> 子类构造器
   */
  class Animal() {
    println("父类构造器被调用.....")
  }

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

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

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

image.png