Scala的繼承

541732025發表於2015-11-16

點選(此處)摺疊或開啟

  1. class Person1(val name : String, var age : Int){
  2.   println("The primary constructor of Person")
  3.   val school = "BJU"
  4.   def sleep = "8 hours"
  5.   override def toString = "I am a Person1!"
  6. }
跟在java中一樣,任何class都是預設繼承自object,這裡override了toString方法

點選(此處)摺疊或開啟

  1. class Worker(name : String, age : Int, val salary : Long) extends Person1(name, age){ //建立Worker例項時,也會使用name、age填充父類例項。子類也必須將父類的主構造器的引數填滿
  2.   println("This is the subClass of Person, Primary constructor of Worker")
  3.   override val school = "Spark" //覆蓋父類的屬性
  4.   override def toString = "I am a Worker!" + super.sleep //super呼叫父類的方法
  5. }

點選(此處)摺疊或開啟

  1. object OverrideOperations{
  2.   def main(args: Array[String]) {
  3.     val w = new Worker("Spark", 5, 100000)
  4.     println("School :" + w.school)
  5.     println("Salary :" + w.salary)
  6.     println(w.toString())
  7.   }
  8. }

結果:
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 //子類覆蓋

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-1839810/,如需轉載,請註明出處,否則將追究法律責任。

相關文章