类的继承

46 阅读1分钟

image.png

继承的概念和基本语法

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

class 子类名 extends 父类名 { 类体 }

package level02

import java.io.FileWriter

object base08 {
  /*
   * 继承
   * 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

问??

1、如果子类觉得父类的方法并不是自己想要的,如何定义自己的方法呢?

override

package level02

import java.io.FileWriter

object base08 {
    /*
     * 继承
     * extends
     * 好处: 不劳而获
     * 
     * 问题:
     * 如果子类觉得父类的方法并不是自己需要的,如何定义自己的方法呢?
     * */
    class Animal() {
      def eating(): Unit = {
        println("Animal eating")
      }
    }

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

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

image.png 2、如果子类还想调用父类的方法怎么办?

super

package level02

import java.io.FileWriter

object base08 {
    /*
     * 继承
     * extends
     * 好处: 不劳而获
     *
     * 问题:
     * 如果子类觉得父类的方法并不是自己需要的,如何定义自己的方法呢?
     * 1.override 重写
     * 2.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.eating()
        println("我是狗,我有自己的吃饭的方式!")
      }
    }

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