天天看點

好程式員大資料學習路線分享Scala系列之抽象類

好程式員大資料學習路線分享Scala系列之抽象類

1抽象類的定義

定義一個抽象類:

如果某個類至少存在一個抽象方法或一個抽象字段,則該類必須聲明為abstract。

abstract class Person{

//沒有初始值,抽象字段

var name:String

//沒有方法體,是抽象方法

def id: Int

}

class Employ extends Person{

var name:String="Fred"

//實作,不需要overide關鍵字

def id = name.hashCode

}

2抽象類的應用

定義帶有抽象類型成員的特質:

trait Buffer {

  type T

  val element: T

}

定義一個抽象類,增加類型的上邊界

abstract class SeqBuffer extends Buffer {

  type U

  //

  type T <: Seq[U]

  def length = element.length

}

abstract class IntSeqBuffer extends SeqBuffer {

  type U = Int

}

abstract class IntSeqBuffer extends SeqBuffer {

  type U = Int

}

//使用匿名類将 type T 設定為 List[Int]

def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer =

  new IntSeqBuffer {

       type T = List[U]

       val element = List(elem1, elem2)

     }

val buf = newIntSeqBuf(7, 8)

println("length = " + buf.length)

println("content = " + buf.element)

繼續閱讀