Scala inheritance

  • The child class inherits the parent class and will inherit all the methods and properties of the parent class except private.

Inherit the main constructor of the parent class

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}"
}

Auxiliary constructor that inherits the parent class

// 继承父类的辅助构造器  要声明父类辅助构造器,同时子类的主构造器也要包含父类构造器的参数
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)


  }
}

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114446482