scala抽象类实战

实战一:

声明一个抽象类(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,对于一个事件来说,事件名称决定他的不同,所以名称是不可变的,可以将时间和内容的不同来区分不同的事件

/**
  * 事件的抽象类,由事件的三要素组成,事件名称、发生时间(时间戳)
  * 事件内容
  * @param name 事件名称
  */
abstract class Event(val name:String) {
  var time:Long
  var content:String
}

 

 子类基本事件类,子类必须实现父类的未实现的属性的方法,如果不想先初始化,可以用占位符先占用位置,子类中有apply的方法重载。

/**
  * 基本事件类,继承时间的抽象类
  * @param name 事件名称
  */
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

 

posted @ 2016-07-05 11:31    阅读(2625)  评论(0编辑  收藏  举报