Scala继承

  • 子类继承父类,会继承父类中除了私有的全部方法和属性。

继承父类的主构造器

object Scala06_Extends {
  def main(args: Array[String]): Unit = {
    // 自动类型推导不能推断出多态,需要自己指定
    val stu: Person06 = new Student06()  // 1 3

    val stu: Person06 = new Student06("1001")   // 1 3 4
    stu.name = "lisi"
    stu.age = 21
    println(stu)
  }
}

class Person06 {
  println("1.父类的主构造器....")
  var name: String = _
  var age: Int = _

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

// 继承父类的主构造器
class Student06 extends Person06{
  println("3.子类的主构造器....")

  var stuId: String = _

  def this(stuId: String) {
    this()
    println("4.子类的辅助构造器")
    this.stuId = stuId
  }

  override def toString: String = s"name = ${name}, age = ${age}, stuId = ${stuId}"
}

继承父类的辅助构造器

// 继承父类的辅助构造器  要声明父类辅助构造器,同时子类的主构造器也要包含父类构造器的参数
class Teacher(name: String, age: Int) extends Person06(name, age) {
  println("5.子类的主构造器")
  var tId: String = _

  def this(name:String, age:Int, tId: String) {
    // 调用主构造器
    this(name,age)
    println("6.子类的辅助构造器")
    this.tId = tId
  }

  override def toString: String = s"name = ${name}, age = ${age}, tId = ${tId}"
}

object Scala06_Extends {
  def main(args: Array[String]): Unit = {
    val teacher: Person06 = new Teacher("李明",25)   // 1 2 5
    println(teacher)

    val teacher2: Person06 = new Teacher("李明",25, "1001")  // 1 2 5 6
    println(teacher2)


  }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页