Scala的继承和多态

基本语法

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

其中:
(1)子类继承父类的属性和方法
(2)scala 是单继承

案例实操

(1)子类继承父类的属性和方法
(2)继承的调用顺序:父类构造器->子类构造器

package chapter06

object Test07_Inherit {

  def main(args: Array[String]): Unit = {

    val student1 = new Student7("ailce",12)
    val student2 = new Student7("bob",12, "std001")

    val teacher = new Teacher()
    teacher.printInfo()

    val person = new Person7()

    def personInfo(person: Person7): Unit ={
      person.printInfo()
    }

    personInfo(student1)
    personInfo(teacher)
    personInfo(person)


  }

}

//定义一个父类
class Person7(){

  var name: String = _
  var age: Int = _

  println("1.父类的主构造器调用")

  def this(name: String , age:  Int){
    this()
    println("2.父类的辅助构造器调用")
    this.name = name
    this.age = age
  }

  def printInfo(): Unit ={
    println(s"Person: $name, $age")
  }
}

//定义子类
class Student7(name: String, age: Int) extends Person7(){

  var StdNo: String = _

  println("3,子类的构造器被调用")

  def this(name: String, age: Int, stdNo: String){

    this(name,age)
    println("4.子类的辅助构造器调用")
    this.StdNo = stdNo

  }

  override def printInfo(): Unit = {
    println(s"Student: $name, age: $age, StdNo: $StdNo")
  }

}

class Teacher extends  Person7{
  override def printInfo(): Unit = {
    println(s"Teacher: $name, age: $age")
  }
}

(3)动态绑定 :Scala 中属性和方法都是动态绑定,而 Java中只有方法为动态绑定。

package chapter06

object Test08_DynamicBind {

  def main(args: Array[String]): Unit = {


    //属性和方法都是动态绑定
    val student : Person8 = new Student8
    println(student.name)

    student.hello()

  }

}

class Person8{
  val name : String = "person"

  def hello(): Unit ={
    println("person,hello")
  }
}

class  Student8 extends Person8{

  override val name : String = "student"

  override def hello(): Unit ={
    println("student,hello")
  }

}


结果截图
Scala的继承和多态

上一篇:从word中复制内容包含图片到网页编辑器中


下一篇:illustrator插件--常用功能开发--测量路径长度--js脚本开发--AI插件