Scala的继承

class Person1(val name : String, var age : Int){
  println("The primary constructor of Person")
  val school = "BJU"
  def sleep = "8 hours"
  override def toString = "I am a Person1!"
}

跟在java中一样,任何class都是默认继承自object,这里override了toString方法

class Worker(name : String, age : Int, val salary : Long) extends Person1(name, age){ //创建Worker实例时,也会使用name、age填充父类实例。子类也必须将父类的主构造器的参数填满
  println("This is the subClass of Person, Primary constructor of Worker")
  override val school = "Spark" //覆盖父类的属性
  override def toString = "I am a Worker!" + super.sleep //super调用父类的方法 
}
object OverrideOperations{
  def main(args: Array[String]) {
    val w = new Worker("Spark", 5, 100000)
    println("School :" + w.school)
    println("Salary :" + w.salary)
    println(w.toString())
  }
}

结果:
The primary constructor of Person //先构造父类(跟java一样)
This is the subClass of Person, Primary constructor of Worker //构建子类
School :Spark // 属性被覆盖
Salary :100000 //子类属性
I am a Worker!8 hours //子类覆盖

你可能感兴趣的:(Scala的继承)