TOP

scala抽象類實戰
2017-10-10 12:11:58 】 瀏覽:9269
Tags:

實戰一:

聲明一個抽象類(SuperTeacher):(超級老師)

abstract class SuperTeacher(val name : String){
  var id : Int
  var age : Int
  def teach
}

 一個不可變屬性,和兩個可變屬性(主鍵和年齡),一個未實現方法(教書)

聲明一個子類(TeacherForMaths):

class TeacherForMaths(name : String) extends SuperTeacher(name){

  override var id = name.hashCode()
  override var age = 29
  override def teach{
    println("Teaching!!!")
  }
}

 抽象類的測試類

object AbstractClassOps{
  def main(args: Array[String]) {
	  val teacher = new TeacherForMaths("Spark")
	  teacher.teach

	  println("teacher.id" + ":" + teacher.id)
	  println(teacher.name + ":" + teacher.age)

  }
}

 實戰二:

 抽象事件類:event,對于一個事件來說优乐棋牌app下载,事件名稱決定他的不同,所以名稱是不可變的,可以將時間和內容的不同來區分不同的事件


abstract class Event(val name:String) {
  var time:Long
  var content:String
}

 

 子類基本事件類,子類必須實現父類的未實現的屬性的方法,如果不想先初始化,可以用占位符先占用位置优乐棋牌app下载,子類中有apply的方法重載。

class BaseEvent(name: String) extends Event(name) {
  var id: String = _
  override var time: Long = _
  override var content: String = _

  override def toString():String ={
    id+","+name+","+time+","+content
  }

}

 


 

object BaseEvent {
  def apply(name: String): BaseEvent = {
    val event = new BaseEvent(name)
    event
  }

  def apply(name: String, id: String): BaseEvent = {
    val event = apply(name)
    event.id = id
    event
  }

  def apply(name: String, id: String, time: Long): BaseEvent = {
    val event = apply(name, id)
    event.time = time
    event
  }

  def apply(name: String, id: String, time: Long, content: String): BaseEvent = {
    val event = apply(name, id, time)
    event.content = content
    event
  }

  def main(args: Array[String]) {
    val event = BaseEvent("name","shsh001",1200132392838L,"scjsncjscnsncas");
    print(event.toString())
  }
}

 


 執行結果:

shsh001,name,1200132392838,scjsncjscnsncas

 

請關注公眾號獲取更多資料



】【打印繁體】【】【】 【】【】【】 【關閉】 【返回頂部
上一篇Scala編寫的打印乘法口訣和金字塔 下一篇Scala編程之訪問修飾符